Several different equals methods

Hi,
I want to compare two different sets with eachother. The Set contains objects with a number of strings and Integers, and some of these need to be equal in order to find a match between the two different Sets. This differs from the "natural order" or the actual equal-value for the two objects, so I don�t want to implement Comparable and use the equals method directly in my Objects since I do not wat to mess with the "truth".
I tried to used Comparator, but the equals(Object obj) method only provides one of the two objects I need to compare, and the compare(Object obj1, Object obj2) is good, but should I use it to compare two objects from two DIFFERENT Collections. It seems the compare method is mostly used for sorting, and I don�t care about sorting at this point.
Set<MyObject> set1;
Set<MyObject> set2;
//compare all the objects in set 1 to all objects in set2 AND, if there is a match do:
myObjectFromSet1.setACertainValue(myObjectFromSet2.getACertainValue);The "ACertainValue" is of course not included in the comparison, since in set1, all the "ACertainValues" are empty, but I need to pick the value from its "equal" object from set2.

I compare them field by field in my object - strings
and Integers - (except for one field : position).
All must match to call them "equal". Then I want to
set that field (position) in the set that doesn�'t
have that info yet and pick the value from the other
set (where there is ONE corresponding Object
available only). After this the two objects from each
set are "really equal".
There might be objects available without a match, but
those I will handle seperately.
Thanks for taking you time, it is really appriciated.No problem. I think I understand what you mean, here's yet another little demo:import java.util.*;
public class Main {
    public static void main(String[] args) {
        MyObject[] array1 = {new MyObject(1, "A", new Integer(11)),
                             new MyObject(2, "B", new Integer(22)),
                             new MyObject(3, "C", new Integer(33))};
        Set<MyObject> set1 = new HashSet<MyObject>(Arrays.asList(array1));
        MyObject[] array2 = {new MyObject(1, "A"),
                             new MyObject(2, "B"),
                             new MyObject(3, "C")};
        Set<MyObject> set2 = new HashSet<MyObject>(Arrays.asList(array2));
        System.out.println("Before\nset1 : "+set1);
        System.out.println("set2 : "+set2);
        List<MyObject> list1 = new ArrayList<MyObject>(set1);
        for(MyObject mo2 : set2) {
            int index = list1.indexOf(mo2);
            if(index != -1) {
                MyObject mo1 = list1.get(index);
                if(mo2.position == null) {
                    mo2.position = mo1.position;
                } else {
                    mo1.position = mo2.position;
        System.out.println("\nAfter\nset1 : "+set1);
        System.out.println("set2 : "+set2);
class MyObject {
    protected Integer id, position;
    protected String str;
    public MyObject(int id, String str) {
        this(id, str, null);
    public MyObject(int id, String str, Integer position) {
        this.id = id;
        this.str = str;
        this.position = position;
    public boolean equals(Object o) {
        MyObject that = (MyObject)o;
        return this.id == that.id && this.str.equals(that.str);
    public int hashCode() {
        return (31*this.id) ^ (37*this.str.hashCode());
    public String toString() {
        return "{id="+this.id+", str="+this.str+", position="+this.position+"}";
}Produces the following output:Before
set1 : [{id=3, str=C, position=33}, {id=2, str=B, position=22}, {id=1, str=A, position=11}]
set2 : [{id=3, str=C, position=null}, {id=2, str=B, position=null}, {id=1, str=A, position=null}]
After
set1 : [{id=3, str=C, position=33}, {id=2, str=B, position=22}, {id=1, str=A, position=11}]
set2 : [{id=3, str=C, position=33}, {id=2, str=B, position=22}, {id=1, str=A, position=11}]

Similar Messages

  • What would be the result if we overrode the equals method properly

    import java.util.*;
    class Nearly{
       String value:
       Nearly(String v){ value = v;}
       public int hashCode(){ return 1;}
       public boolean equals(Nearly n){
       if(value.charAt(0) == n.value.charAt(0)) return true;
       return false;
       public static void mian(String [] sss){
         Nearly n1 = new Nearly("aaa");
         Nearly n2 = new Nearly("aaa");
         String s = "_";
         if(n1.equals(n2)) s += "1";
         if(n1==n2) s += "2";
         Set <Nearly> set = new HashSet <Nearly>();
          set.add(n1);
          set.add(n2);
         System.out.println(s + " " + set.size());
    }Ans: b) -1 2
    Reason: Two different equals() methods are invoked, because the equals() method shown in the code doesn't properly override Object.equals(), which takes an Object
    Ok so what would have been the result if the equals() method was something like this:
    public boolean equals(Object n)
    {I guess my question is about the overriding the equals() method which i am not able to understand

    pksingh79 wrote:
    what would be the result if we overrode the equals method properlyThe result would be a method, the functionality of which would adhere to Object#equals()'s contract:
    public boolean equals(Object obj)
    Indicates whether some other object is "equal to" this one.
    The equals method implements an equivalence relation on non-null object references:
    &#42; It is reflexive: for any non-null reference value x, x.equals(x) should return true.
    &#42; It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and
    only if y.equals(x) returns true.
    &#42; It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and
    y.equals(z) returns true, then x.equals(z) should return true.
    &#42; It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y)
    consistently return true or consistently return false, provided no information used in equals
    comparisons on the objects is modified.
    &#42; For any non-null reference value x, x.equals(null) should return false.

  • Windows Explorer was crashing/restarting every few seconds and after trying several different methods of fixes, the only one that worked was removing Firefox, is there something I've missed that I can get Firefox back?

    I'm running a Toshiba Satellite laptop that was originally running Windows Vista 32-bit, but was upgraded by me to Windows 7 32-bit. On Windows Vista, all I would run was Firefox. I loved it!!! On Windows 7, I've noticed that Firefox kept hanging whenever I would try to download a file...from anywhere. I got so frustrated I went to try several different browsers. They all worked extremely quickly, whereas Firefox was working so slow, I could click on a link to a page, go get some lunch, come back and it still be trying to load the page. This was drastically unusual for Firefox. I used the other browsers and everything was fine for a week and then Windows Explorer started going down every few seconds. I went to the windows 7 forums and started looking. There were several suggestions on how to fix the problem, none of which worked for my compy. I tried restarting the compy in safe mode. That didn't help. I turned off every startup program except for the essentials and that DID work in keeping Windows Explorer from restarting. I then dove into the tedious task of trying to discern which 3rd party program was the offender. I removed everything from my compy that had been downloaded in the last ten days (well before the windows explorer issue, but not before the firefox issue). That didn't work either. I tried replacing an explorer file, which didn't work either. There were several other things I tried, as well, but nothing worked. Then, I saw a post that Firefox had caused the problem for one person. I went in and did as was suggested and completely removed Firefox and all associated files. Unfortunately, this worked. I haven't had any more trouble with windows explorer restarting. My big problem is, however, I can't run Firefox!!! And I LOVE Firefox!!! It's spoiled me! I hate Internet explorer, which is what I'm forced to run now. I've tried Safari and Google Chrome and don't like either one of those, either. I want my Firefox back! But if it's not working 100% it's less frustrating to be forced to live with the Internet Explorer. I'm going insane, here! Does anyone have any suggestions? I tried clearing out browser history, changing download files and a couple of other things and nothing worked with the Firefox to get it going better before I started having the Windows Explorer difficulty and had to completely erase the Firefox program. If I've missed any info, please don't hesitate to ask!! I'm happy to supply whatever I know about the issue!!

    uninstalled firefox ....deleted all files still remaining under mozilla firefox directory in program files ... to avoid having to reprogram all my settings, reisntall all addons as well .. I did not remove anything from mozilla firefox that is stored in either appdata or under the windows users directory (if any)
    ... the as suggested reinstalled the latest version of the firefox browser using the link you provided in the email ..; tested and several issues still remain present and unresolved ....
    so please this is urgent or I will have to jump browsers and start using chrome .. because we work 14 hours a day 6 (sometimes 7) days a week, to get ready for the launch of our newest venture and we cannot lose that much days on browser related issues ... so please instead of putting me through week long step process .. of do this .. do that .. can you please actually look into the issue from your end .. I use firefox for so many, many years thta I deserve this kind of support .. thnx Robert

  • Why do we need to override Hascode and Equals method?

    Hi,
    == checks if the two references are equal and .equlas will check if the value is same, if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).
    Please someone elaborate on this and also tell me what role hashcode plays in this.
    thanks
    Anirudh

    anirudh1983 wrote:
    if we want .equals to take care of both reference and value are correct. why cant I just override equals with an extra check that references are equal(==).Many equals() methods do run an '==' check first for efficiency (and I would recommend it if you're writing one yourself).
    Please someone elaborate on this and also tell me what role hashcode plays in this.The reason that it is good practise to override equals() and hashCode() together is to maintain consistency.
    Hashcodes are used by all Java collections that contain the word 'Hash' in their name, and may also be used by other programs that need a hash code for identification; so if you supply one, you must follow the rules (which you can find in the API for Object.equals() and Object.hashCode()).
    The main rule is this: *objects that are equal() must have equal hashcodes*.
    Note that the reverse is NOT true: objects that are not equal() do not have to have different hashcodes, but it is usually better if they do.
    There is quite a lot to know about hashcodes, and what makes a good one, so I suggest you follow dcminter's advice if you want to be a happy and prosperous Java programmer.
    Winston

  • String equal method Vs Object equal method.

    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.

    RGEO wrote:
    hello, Can anybody explain me difference between equal method in String class and equal method in Object class. We have equal method in object classes. and object class is the super class of all classes, so why we need equal method in String class.Because "equal" means different things for different objects. For a String, "equal" would mean that both Strings being compared have the exact same characters, in the same sequence. For an Integer, "equals" would mean that both objects have the same integer value.

  • Org.jcp.xml.dsig.internal.dom.DOMKeyInfo equals() method implementation

    I use something like this:
    if(myKeyInfo.equals(anotherKeyInfo))
    //I believe two signers are same. It seems correct.
    Behind the scene the KeyInfo is implemented by org.jcp.xml.dsig.internal.dom.DOMKeyInfo.
    I would like to have a look at org.jcp.xml.dsig.internal.dom.DOMKeyInfo to find out how its equals method is implemented.
    Basically I would like to make sure wether myKeyInfo.equals(anotherKeyInfo) is the right way to ascertain the signer.

    You can find the source in a few different places, either in the Apache XML Security project repository or the JDK 6 and OpenJDK projects on java.net. Here is a pointer to the JDK 6 source:
    https://jdk-jrl-sources.dev.java.net/source/browse/jdk-jrl-sources/jdk6/trunk/j2se/src/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyInfo.java?rev=3&view=log

  • Need a Effective Design Pattern for Different Validation methods ???

    Hi All,
    I am having different validation methods with separate functions. I like to know the Best and Effective Design Pattern to do this.
    for example
    validateUserId()
    validatePassword()
    validateAuthentication()
    validateSession()
    validateConnection()
    .... etc......
    Can anybody help me to solve this?
    Thanks,
    J.Kathir

    Hi there - is this the kind of thing you wanted?.
    This structure has served me well. There is quite a lot to it and lots you need to infer but you should be able to work it out!
    It works for EJB & swing etc (I believe)..
    It doesn't use exceptions to return validation messages.
    It doesn't use lots of little objects. The code is very explicit & pretty simple.
    public class PersonValidator
    Person myData;
    public PersonValidator() {
    //personId will be 0 and we are in nsert mode
    myData = new Person();
    public PersonValidator(long personId) {
    //personId will have a value and we are in update mode
    myData = PersonDb.getPerson(personId);
    // =================================Single field validation
    // =================================For swing apps to call - not over network.
    // =================================Use validateData method
    public String validateDateOfBirth(String dataOfBirthStr) {
    String msg = "";
    msg = validateDateStr(dataOfBirthStr);
    if (!msg.equals("")) return msg;
    public String validateSurname(String surname) {
    String msg = "";
    if (surname.equals("")) return "surname must be entered";
    //=============================================Cross Validation
    public List crossValidateAndSave(boolean saveData) {
    String msg = "";
    List valerrs = new ArrayList();
    if (surname.equals("Collins") && dateOfBirth.compareTo("???")) {
    List.add("Candidate is lying about their age. Please enter a realistic Date of birth");
    if (valerrs.size() == 0) {
    if (saveData()) {
    personDb.saveData(myData);
    // =========================To validate across the netwrok this lets you
    // pass all the data in 1 go & receive multiple messages in reply.
    // AN EJB can delegate to this code or this code could be in the EJB.
    // @param stopAtFirstMessage flag allow efficiency if app ccan't handle multiple validation
    // erros at a time.
    // @param saveData flag allows validation without saving - allows for confirm message.
    // @param EditPersonGuiData - What the user types in. Numeric data & dates can be
    // in Strings. Using struts this could be the formBean.
    public List validateData(EditPersonGuiData inputData, boolean stopAtFirstMessage, boolean saveData) {
    String msg = "";
    List valerrs = new ArrayList();
    msg = validateDateOfBirth(inputData.dateOfBirth);
    if (!msg.equals("")) valerrs.add(msg);
    if (stopAtFirstMessage) return valerrs;
    valerrs = crossValidateAndSave()
    return valerrs;
    }

  • I have an old Frank Sinatra CD called duets which I have imported but it has separated into several different albums one per track?How can I merge into the one album?s

    Can somebody advise how to remerge what has been imported as several different tracks into the original Album format?

    If you select the tracks all together in iTunes/ Songs then go to File/Get info you will be asked "Are you sure you want to edit information for multiple items?" Go ahead and you can make them into an album, putting in the artist name, etc.

  • ITunes 12 is making 1 album become several different albums with the same tracks.  How do I combine them again?

    I had an issue in past versions of iTunes, where I would rip a CD and, for some reason, iTunes would turn it into several different CDs instead of just one, even though everything about the album was the same (as in same artist, same album name, same year, etc).  It seems as though that issue has returned and one album with 6 tracks is now 3 albums (1 album has 1 song, another has 2 and the third has 3).  Yet, it's all the same album.  I re-entered the data for the album name and artist, but it doesn't work like the previous versions.  Anyone have any ideas why this is happening (other then bugs) or how to fix it?

    Apple's official advice is here... HT2905 - How to find and remove duplicate items in your iTunes library. It is a manual process and the article fails to explain some of the potential pitfalls.
    Use Shift > View > Show Exact Duplicate Items to display duplicates as this is normally a more useful selection. You need to manually select all but one of each group of identical tracks to remove. Sorting the list by Date Added may make it easier to select the appropriate tracks, however this works best when performed immediately after the dupes have been created.  If you have multiple entries in iTunes connected to the same file on the hard drive then don't send to the recycle bin. This can happen, for example, if you start iTunes with a disconnected external drive, then connect it, reimport from your media folder, then restart iTunes.
    Use my DeDuper script if you're not sure, don't want to do it by hand, or want to preserve ratings, play counts and playlist membership. See this thread for background. Please take note of the warning to backup your library before deduping, whether you do so by hand or using my script, in case something goes wrong.
    (If you don't see the menu bar press ALT to show it temporarily or CTRL+B to keep it displayed)
    tt2

  • Can I print several different pics of the same size on one shee  of papert?

    Hi,
    I should like to print a group of several different pics of the same size & resolution on one sheet of (A4) paper eg 6 family photos. There doesn't seem to be a template for this - just two choices of format (both with one large and a few smaller format) and there is no 'Printer' pop up menu.
    I tried to laboriously copy pics to a two column works word processing document (after resizing in a different one so that they would fit in the columns). This is time consuming and when down sizing the pics lose resolution!
    Maybe I can download templates somewhere on the apple site as suggested by apple care but I couldn't find out where. Maybe there is a possibility of doing some contact prints?
    Any help much appreciated - many thanks - John

    Select the 6 photos you want printed in the iPhoto Library or Album window.
    Choose File->Print.
    In the Print dialog box, Select the paper size in the Paper popup menu.
    In the Style popup menu, select N-Up.
    In the Photos per page popup select 6.
    The preview should show what you'll get. I hope its what you wanted.
    Message was edited by: Thomas Emmerich

  • Is there a way to order several different iPhoto projects at one time, on the same order? (to avoid paying shipping on each individual project?)

    Is there a way to order several different iPhoto projects at one time, on the same order? (to avoid paying shipping on each individual project?)

    No, unless they're all prints.
    (117535)

  • Hi my iPhone 4 won't turn on . When plugged in on several different chargers the following happens .  Blank screen then apple sign for a short period then it buzzes and goes blank. When connected to mac  get message that phone is in recovery mode and that

    Hi  my iPhone 4 won't turn on . When plugged in on several different chargers the following happens .  Blank screen then apple sign for a short period then it buzzes and goes blank. Have tried power button and home button but no change ,When connected to mac  get message that phone is in recovery mode and that i must restore this phone before it can be used with iTunes . Is this my last resort as I have some photoessays I don't want to loose.
    PPlease help

    Hello, Chantal105
    Thank you for visiting Apple Support Communities. 
    If your device is in recovery mode you will need to restore the device. 
    If you can't update or restore your iOS device
    http://support.apple.com/kb/HT1808
    Cheers,
    Jason H.

  • My Equal method is not working in array person!!! help me pls

    My assignment is to create an application program that declares an array of 100 components of type person. add a person into the array and (CHECK DUPLICATE ENTRIES ARE NOT ALLOWED)
    my code is(this is in another class):
    public Boolean equals(Person p1){
              return(name == p1.name&&address == p1.address&&telephoneNo == p1.telephoneNo&&email == p1.email);
    Become(this is in my main class):
    public static boolean isEquals(Person p1)
              if(Person.getPersonCount()==1)
                   return false;
              for(int i=0;i<Person.getPersonCount()-1;i++)
                   if(p1.equals(p))
                        return true;
              return false;
    my output code is:
    public static void addPerson()
              String name, address, telephoneNo, email;
              int count=Person.getPersonCount();
              int numberPerson = Integer.parseInt(JOptionPane.showInputDialog(null,
                   "Enter number of person you want to add in (1 to 100):","Person Adding Table",
                   JOptionPane.QUESTION_MESSAGE));
              for(int i=0;i<numberPerson;i++)
                   name = JOptionPane.showInputDialog(null,"Please enter a person name:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   address = JOptionPane.showInputDialog(null,"Please enter a person address:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   telephoneNo = JOptionPane.showInputDialog(null,"Please enter a person telephone number:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   email = JOptionPane.showInputDialog(null,"Please enter a person email address:","Person No."+(i+1+count),JOptionPane.QUESTION_MESSAGE);
                   p[i+count]=new Person(name,address,telephoneNo,email);
                   if(isEquals(p[i+count]))
                        System.out.println("Please take note! Your person details have duplicate data...");
              System.out.println("You has added "+numberPerson+" details of person!!!");

    Don't compare Strings with ==. Use the equals() method.
    if (string1.equals(string2))Using == checks if they are the exact same object (think of it as the same location in memory). The equals() method checks if their contents are equal...just like you're trying to set up for your Person class. You want to see if the various fields of a Person object are the same...not if they are in fact the same object.

  • I've tried to install flash player several different times ans each time i get a connection error message.It downloads fine and when i run the file to start install,it installs up to 5% and then i get the connection error message.Can someone please help m

    I've tried to download the flash player several different times and each time i get a connection error message.It downloads fine and when i run the file to start install, it installs up to 5% and then i get the connection error message. I've tried disabling my antivirus software, closing my browser for install and nothing.Can someone please help me? I'm using Firefox.

    Hi!
    I had the exact same issue, being on a mac. If you are on a mac and the connection error message occurs, then use this link http://fpdownload.macromedia.com/pub/flashplayer/latest/help/install_flash_player_osx.dmg
    It allows you to download it offline, which is what I used.
    Hope I was help!
    -Haroon

  • HT2693 The sound will no longer come through my headphones on my iPad I've tried several different headsets.  The sound works as normal without the headphones but will still not come through the headphones even thoug I have tried to reset it twice. Please

    The sound will no longer come through my headphones on my iPad I've tried several different headsets.  The sound works as normal without the headphones but will still not come through the headphones even thoug I have tried to reset it twice. This is the new ipad with retina display and is only 2 months old and otherwise works fine. Please help!

    - Try cleaning out/blowing out the headphone jack. Try inserting/removing the plug a dozen times or so.
    Try the following to rule out a software problem
    - Reset the iPad. Nothing will be lost
    Reset iPad: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Reset all settings
    Go to Settings > General > Reset and tap Reset All Settings.
    All your preferences and settings are reset. Information (such as contacts and calendars) and media (such as songs and videos) aren’t affected.
    - Restore from backup
    - Restore to factory settings/new iPod.
    - Make an appointment at the Genius Bar of an Apple store. Seems you have a bad headphone jack.
    Apple Retail Store - Genius Bar
    Apple will exchange your iPad for a refurbished one for this price. They do not fix yours.
    iPad Service Answer Center                 
    A third-party place like the following will replace the jack for less. Google for more.
    iPhone Repair, Service & Parts: iPod Touch, iPad, MacBook Pro Screens
    Replace the jack yourself
    iPad Repair - iFixit

Maybe you are looking for