- boolean contains(Object o) 判断集合中是否包含某个对象o,如果包含返回true,底层调用了equals方法。
- 放在集合中的元素要重写equals方法,不然比较的是地址。
- demo
package collection;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionTest04 {
public static void main(String[] args) {
Collection c =new ArrayList();
String s1 = new String("abc");
c.add(s1);
String s2 = new String("def");
c.add(s2);
System.out.println(c.size());
String x = new String("abc");
System.out.println(x.equals(s1));
System.out.println(c.contains(x));
}
}
package collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
public class CollectionTest03 {
public static void main(String[] args) {
Collection c = new ArrayList();
User u1 = new User("Jack");
User u2 = new User("Jack");
c.add(u1);
System.out.println(c.contains(u2));
}
}
class User{
private String name;
public User(){};
public User(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name);
}
}