1

When im using an ArrayList

 ArrayList<item> List = new ArrayList<item>();

 Item a = new Item(1,"Book");
 Item b = new Item(2,"Shoes");

 List.add(a);
 List.add(b);

 Item c = new Item(1,"Book");

 if(List.equals(c)) //Will this code return true?

if not, can anyone tell in what case List.equals(c) will return true. Because an item can have many attributes, id, name, price. Does it check for the reference name ? or compare the attributes.

2
  • 2
    you're in Java world so in free time take a look at java naming convension Commented Mar 27, 2011 at 13:56
  • yeah i got a lot of comments about that.. i will do so Commented Mar 27, 2011 at 14:06

3 Answers 3

3

First of all, you must use contains method not equals. Contains checks if an item is in the list. But equals checks if a list is equal to another list.

Now to your question - Contains will look for the implementation of equals method(the one inherited from Object). By default it compares references. If you want to compare attributes, override it to use custom comparison logic.

Sign up to request clarification or add additional context in comments.

Comments

1

From sun's doc about equals.

chack here http://download.oracle.com/javase/1.4.2/docs/api/java/util/List.html#equals(java.lang.Object)

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

Comments

1

No, it'll return false because c isn't equals with list. Equals means equals :) so you want to use contain method:

list.contains(c);

More details: In java source you can find what exactly means equals when you're calling it on ArrayList:

public boolean equals(Object o) {
    if (o == this)
        return true;
    if (!(o instanceof List)) // your object IS NOT instanceof with List interface
        return false;
    ...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.