黑马程序员技术交流社区
标题:
为什么打印的人名是内存地址值,不是人名?
[打印本页]
作者:
程志远
时间:
2015-4-11 23:36
标题:
为什么打印的人名是内存地址值,不是人名?
import java.util.*;
class Student implements Comparable<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(new Integer(s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
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 toSting()
{
return name+":"+ age;
}
}
class MapTest
{
public static void main(String[] args)
{
HashMap<Student,String> hm = new HashMap<Student, String>();
hm.put(new Student("lisi1",21),"beijing");
hm.put(new Student("lisi2",22),"nanjing");
hm.put(new Student("lisi3",23),"nanjing");
hm.put(new Student("lisi4",24),"wuhan");
//第一种取出方式
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext())
{
Student stu = it.next();
String addr = hm.get(stu);
System.out.println(stu+".."+addr);
}
/* //第二种取出方式 entrySet
Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
Iterator<Map.Entry<Student,String>> iter = entrySet.iterator();
while (it.hasNext())
{
Map.Entry<Student,String> me = iter.next();
Student stu = me.getKey();
String addr = me.getValue();
System.out.println(stu+"....."+addr);
}*/
}
}
[img]捕获.PNG1.PN[/img]
复制代码
作者:
waylent
时间:
2015-4-11 23:45
Student里的toString()方法拼错了
作者:
殷俊
时间:
2015-4-11 23:46
不能直接打印人名,因为键里面是两个参数,计算机又不知道你要打印哪个,因此你要指定,比如stu.getName();
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2