#1
  1. <?PHP user_title("gimp"); ?>
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2005
    Location
    Internet
    Posts
    7,652
    Rep Power
    6084

    ArrayList.contains(Object) returns false negative - my fault or bug?


    java Code:
    ArrayList<ChatRoom> chatrooms...
    ChatRoom room...
    System.out.println(chatrooms.contains(room));

    false

    java Code:
    ArrayList<ChatRoom> chatrooms...
    ChatRoom room...
    boolean found = false;
    for (int i = 0; i < chatrooms.size(); i++) {
    	if (chatrooms.get(i).equals(room)) { found = true; break; }
    }
    System.out.println(found);

    true


    I don't see what I'm doing wrong, unless ArrayList compares hash codes instead of using Comparable.equals(Comparable) as it says it does in the documentation:

    java Code:
    More formally, returns true if and only if this list contains at least one element e such that
    (o==null ? e==null : o.equals(e))
    taken from java.sun.com's SE 6 API for java.util.ArrayList
    Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
    Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.
    Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
    -Partial Credit: Sun

    If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
    Ches Koblents
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Nov 2004
    Location
    Washington DC
    Posts
    2,756
    Rep Power
    1571
    Here's the actual implementation of contains in java 1.5
    java Code:
     
    //the contains method just checks to see if the value returned from 
        public int indexOf(Object elem) {
    	if (elem == null) {
    	    for (int i = 0; i < size; i++)
    		if (elementData[i]==null)
    		    return i;
    	} else {
    	    for (int i = 0; i < size; i++)
    		if (elem.equals(elementData[i]))
    		    return i;
    	}
    	return -1;
        }


    It looks pretty straightforward. What does your equals method look like?
    I would run this through a debugger or add printlns in your equals method
    Open for extension, closed for modification
  4. #3
  5. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    WDSMIA
    Posts
    10,135
    Rep Power
    5054
    my fault or bug?
    Both. It's your bug and your fault. Mind you, I'm not saying that to be cruel or harsh, but the sooner you realize that the software problems you have are caused by the code you write, the better developer you'll be - by a long shot.

    [EDIT] Just realized the OP is gimp. Gimp, you know better!

    Please post an actual SSCCE; i.e., the bare minimum amount of code that compiles, runs, and correctly demonstrates only the problem and nothing else (please read the link to make sure you understand). That way, we can see the actual implementation you've employed and can get you pointed in the right direction.

    ~

    Comments on this post

    • NovaX agrees
    • gimp agrees : :P
    Last edited by Yawmark; September 3rd, 2008 at 12:04 PM.
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jul 2005
    Location
    Bay Area, California
    Posts
    841
    Rep Power
    1682
    You need to include your equals method, as it may not be symmetric. Also, you should always implement hashCode() when implementing equals(), as per the general contract.
    Note that it is generally necessary to override the <tt>hashCode</tt> method whenever this method is overridden, so as to maintain the general contract for the <tt>hashCode</tt> method, which states that equal objects must have equal hash codes.
  8. #5
  9. <?PHP user_title("gimp"); ?>
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2005
    Location
    Internet
    Posts
    7,652
    Rep Power
    6084
    The SSCCE:

    java Code:
    public class ChatRoom implements Comparable<ChatRoom> {
         private String name;
         private String pass;
         public ChatRoom(String name, String pass) { this.name = name; this.pass = pass; }
         public boolean equals(ChatRoom other) { return name.equals(other.name); }
         public int compareTo(ChatRoom other) { return name.compareTo(other.name); }
    }


    Right, no hashcode implementation.

    As for the part that checks:

    java Code:
    public class Driver {
         public static void main(String[] args) {
              ArrayList<ChatRoom> rooms = new ArrayList<ChatRoom>();
              ChatRoom room1 = new ChatRoom("Name", "pass1");
              ChatRoom room2 = new ChatRoom("Name", "pass2");
              rooms.add(room1);
              System.out.println(rooms.contains(room2));
         }
    }


    because room1.equals(room2) returns true, I thought this should also return true. Guess I shoulda used a hashcode.

    Since the problem was fixed, this is for posterity...
    Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
    Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.
    Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
    -Partial Credit: Sun

    If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
    Ches Koblents
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jul 2005
    Location
    Bay Area, California
    Posts
    841
    Rep Power
    1682
    The problem is that you have not overriden Object#equals(Object o), but instead implemented a seperate ChatRoom#equals(ChatRoom o) method. This is where the @Override annotation can be quite handy, though with experience you'll rarely find yourself hitting this mistake.

    I recommend you read "Effective Java" to understand the importance of a good equals()/hashCode() contract.

    Comments on this post

    • tfecw agrees : I had a feeling that was going to be the issue.
    • gimp agrees : Why, thank you! :) Never ran into this little thing before.
    • mrider agrees
    • Yawmark agrees

IMN logo majestic logo threadwatch logo seochat tools logo