本帖最后由 茄子 于 2014-6-28 15:52 编辑
茄子又着急了!!!!下面是代码,红色字体出,循环不能结束,这是为什么呢????package fifteen_2;
/*
* 每一个学生都有属于自己的归属地,即其所在地,籍贯
* 学生:Student,地址:String
* 学生的属性:
* 姓名,年龄
* 注意,姓名和年龄相同的,视作同一个学生。
* 要保证每一个学生的唯一性。
*
*
* 第一步:描述学生
* 第二部:定义map容器,将学生用作键,地址作为值,存入。
* 第三部,获取map集合中的元素。
* */
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 String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Student s) //为了让学生对象具备比较性,实现了conparable()接口
//这里需要复写compareTo()方法,
{
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 this.name.hashCode()+age*39; //保证hashCode()返回值的唯一性。
}
public boolean equals(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("数据类型不匹配"); //这里可以写成RuntimeException()异常的子类,
//classCastException(),类型转换异常。
Student stu=(Student)obj;
return this.name.equals(stu.name)&&this.age==stu.age;
}
public String toString() //这里覆盖了字符串的toString()方法,,输出时,学生对象,将会自己主动调用该方法。
{
return name+":"+age;
}
}
public class MapTest {
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void TT(String[] args) {
HashMap<Student,String> mp=new HashMap<Student,String>();
mp.put(new Student("zhaoyujie01",21),"beijing");
mp.put(new Student("zhaoyujie02",22),"zhangye");
mp.put(new Student("zhaoyujie02",22),"gansu"); //集合中只有四个元素,而且,甘肃会覆盖zhangye
mp.put(new Student("zhaoyujie03",23),"jiuquan");
mp.put(new Student("zhaoyujie04",24),"newyork");
//方法一:利用keySet方法,进行存取。
Set<Student> set=mp.keySet();
Iterator<Student> it=set.iterator();
while(it.hasNext())
{
Student stu=it.next();
String str=mp.get(stu);
// sop(stu.getName()+"^^^^^^^^^^^^"+stu.getAge()+"^^^^^^^^^^"+str);
sop(stu+str); //在这里,学生对象stu会自己底层调用toString()方法,
}
//方法二,利用entrySet()方法进行获取。
Set<Map.Entry<Student, String>> entrySet=mp.entrySet();
Iterator<Map.Entry<Student, String>> itt=entrySet.iterator();
while(itt.hasNext());
{
Map.Entry<Student,String> me=itt.next();
Student stu=me.getKey();
String add=me.getValue();
sop(stu.getName()+"………………"+stu.getAge()+"…………"+add);
}
}
}
跪求大神解释啊!!!
|