黑马程序员技术交流社区
标题:
Map集合存取,HashCode和Equals方法没有调用
[打印本页]
作者:
571568202
时间:
2015-8-5 19:59
标题:
Map集合存取,HashCode和Equals方法没有调用
package lianxi;
import java.util.*;
import java.util.Map.Entry;
/*1.描述学生。学生属性 :姓名,年龄
2. 定义map容器,将学生作为键,地址作为值,存入
3.获取map容器的元素
*/
public class MapTest_1
{
public static void main(String[] args)
{
Map<Student,String > map= new HashMap <Student ,String >();//定义map容器,将学生作为键,地址作为值
map.put( new Student ("zs1",21), "北京");//将学生信息存入容器内
map.put( new Student ("zs2",22), "天津");
map.put( new Student ("zs3",23),"上海" );
map.put( new Student ("zs4",24),"深圳");
map.put( new Student ("zs1",21),"南京");//是否检测出姓名,年龄重复的学生
//第一种方法 keySet
Set<Student > set =map.keySet();//用keySet方法将map存到Set集合中
Iterator <Student > ite =set .iterator();//迭代器方法
while(ite.hasNext())
{
Student stu= ite.next();
String str= map.get(stu);//获取值
System.out.println(stu+"....."+str);//输出学生信息
}
//第二种方法entrySet
Set<Map.Entry<Student, String>> entryset= map.entrySet();//用entrysetSet方法将map存到Set集合中
Iterator<Map.Entry<Student, String>> it =entryset.iterator();//迭代器方法
while(it.hasNext())
{
Map.Entry<Student, String> mm=it.next();
Student s= mm.getKey();//获取键
String str= mm.getValue();//获取值
System.out.println(s+".............."+str);//输出学生信息
}
}
}
class Student implements Comparable<Student>//Student类
{
private String name;
private int age;
Student (String name, int age)//构造函数
{
this.name= name;
this.age= age;
}
public int compareTo (Student s) //此例子中无效,为了让元素适应二叉树结构
{
int num= new Integer (this.age).compareTo(s.age);
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public int HashCode()//重写哈希表的HashCode方法
{
return name.hashCode()+age*98;
}
public boolean equals (Object obj)//重写哈希表的equals方法
{
if(!(obj instanceof Student))
throw new ClassCastException ("类型异常");
Student s = (Student )obj;
return this.name.equals(s.name) && this.age==s.age ;
}
public String getName()
{
return name;
}
public int getAge ()
{
return age;
}
public String toString ()
{
return name+":"+age;
}
}
复制代码
运行结果
zs3:23.....上海
zs1:21.....南京
zs1:21.....北京
zs2:22.....天津
zs4:24.....深圳
zs3:23..............上海
zs1:21..............南京
zs1:21..............北京
zs2:22..............天津
zs4:24..............深圳
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2