ArrayList objects in Java
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.equ开发者_StackOverflowals(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.
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.
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.
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;
...
}
精彩评论