public class Test{
public static void main(String[]args)throws Exception{
HashMap hm = new HashMap();
hm.put(new StudentKey("200601","200601"),new StudentValue("张三丰","男","计算机","软件工程","20"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("studentData"));
oos.writeObject(hm);
FileInputStream fis = new FileInputStream("StudentData");
ObjectInputStream ois = new ObjectInputStream(fis);
hm = (HashMap)ois.readObject();
System.out.println(hm);
Set set = hm.keySet();
System.out.println(set);
StudentKey sk = new StudentKey("200601","200601");
StudentKey sk1 = new StudentKey("200601","200601");
//下面为什么打印false????
System.out.println(set.contains(sk));
System.out.println(hm.containsKey(sk));
}
}
class StudentKey implements Serializable{
Strin作者: liuzhming 时间: 2013-7-23 22:06
Set的contains()方法用来判断set中是否包含指定元素,如果包含返回true,否则返回false。更确切地讲,当且仅当 set 包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时返回 true。也就是说,指定元素要与set内的元素进行相等性判断,但楼主并没有重写equals方法,那么StudentKey类将继承Object类的equals方法,判断是否指向同一个对象。显然他们不是指向同一个对象,所以返回了false。