A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 张强1 中级黑马   /  2013-7-23 19:48  /  740 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杨兴庭 于 2013-7-24 21:04 编辑

//下面的程序中主方法当中的最后两句为什么打印false??
import java.util.*;
import java.io.*;

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

评分

参与人数 1技术分 +1 收起 理由
杨兴庭 + 1

查看全部评分

1 个回复

倒序浏览
Set的contains()方法用来判断set中是否包含指定元素,如果包含返回true,否则返回false。更确切地讲,当且仅当 set 包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时返回 true。也就是说,指定元素要与set内的元素进行相等性判断,但楼主并没有重写equals方法,那么StudentKey类将继承Object类的equals方法,判断是否指向同一个对象。显然他们不是指向同一个对象,所以返回了false。

评分

参与人数 1技术分 +1 收起 理由
杨兴庭 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马