对于集合List Set Map当调用其方法contains,是不是包含某元素时,会自动调用对象的equals方法,对于ArrayList只需要覆盖对象的equals即可,但对于Set Map,还需要覆盖对象的hashCode,不然得不到预期的结果
测试代码:
public class Name {
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
Name name = (Name)obj;
System.out.println(name.firstName.equals(firstName)&&name.lastName.equals(lastName));
return name.firstName.equals(firstName)&&name.lastName.equals(lastName);
}
@Override
public int hashCode() {
return firstName.hashCode()*lastName.hashCode();
}
}
public class TestContains {
static void testHashSet(){
Set s = new HashSet();
Name name = new Name("hello","world");
s.add(name);
System.out.println(s.contains(new Name("hello","world")));
//System.out.println(s.contains(name));
}
static void testHashMap(){
Map map = new HashMap();
Name name = new Name("hello","world");
map.put(name, name);
System.out.println(map.containsKey( new Name("hello","world")));
}
static void testArrayList(){
List list = new ArrayList();
Name name = new Name("hello","world");
list.add(name);
System.out.println(list.contains(new Name("hello","world")));
}
/**
* @param args
*/
public static void main(String[] args) {
testArrayList();
testHashSet();
testHashMap();
}
}
分享到:
相关推荐
35.能用foreach遍历访问的对象需要实现 ________________接口或声明________________方法的类型。 答:IEnumerable 、 GetEnumerator。 36.GC是什么? 为什么要有GC? 答:GC是垃圾收集器。程序员不用担心内存管理...
Collection是集合类的上级接口,继承与他的接口主要有Set 和List. Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。 10、&和&&的区别。 &是位运算符...
一、Java基础知识 1.Java有那些基本数据类型,String是不是基本...这个方法是由垃圾收集器在确定这个对象没有被引用时对这个对象调用的。它是在 Object 类中定义的,因此所有的类都继承了它。子类覆盖 finalize() ...
Collection是集合类的上级接口,继承与他的接口主要有Set 和List. Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。 13、&和&&的区别。 &是位运算符...
Collection是集合类的上级接口,继承与他的接口主要有Set 和List. Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。 10、&和&&的区别。 &是位运算符...
每一个运行的程序都有自己的消息循环,在循环中得到属于自己的消息并根据接收窗口的句柄调用相应的窗口过程。而在没有消息时消息循环就将控制权交给系统所以Windows可以同时进行多个任务。下面的伪代码演示了消息...
Collection是集合类的上级接口,继承与他的接口主要有Set 和List. Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。 10、&和&&的区别。 &是位运算符...
Map, List<ExcelMap>> dbfield) { List, Object>> list = new ArrayList, Object>>(); HashMap, Object> datamap = null; DealForeign deal = null; // 存放带验证信息的属性 Map, String> iscompare = ...
You would map some input event to a pointer to a function. If you where slick, you would place the configuration information into a file and load the file at run time. Function pointer arrays were ...
This function accepts a string containing a CSS selector which is then used to match a set of elements. The core functionality of jQuery centers around this function. Everything in jQuery is based ...