本帖最后由 黄敏 于 2012-8-15 18:14 编辑
import java.util.*;
class Student{
private String name;
private int age;
private int score;
public Student(String name, int age){
this.setName(name);
this.setAge(age);
//this.setScore(score);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int compareTo(Object obj){
if (!(obj instanceof Student))
throw new RuntimeException("这不是学生类");
Student stu = (Student)obj;
if (this.score > stu.score)
return 1;
if(this.score== stu.score){
this.name.compareTo(stu.name);
}
return -1;
}
}
class MyComparator implements Comparator{
public int compare(Object o1, Object o2){
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int n = new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
if(n==0){
return new Integer(s1.getScore()).compareTo(new Integer(s2.getScore()));
}
return n;
}
}
public class Test10 {
public static void main(String[] args) {
HashMap mp = new HashMap();
mp.put(new Student("张三",17), 89);
mp.put(new Student("李四",18), 90);
mp.put(new Student("王五",17), 91);
Set se = mp.keySet();
Iterator it = se.iterator();
while (it.hasNext()){
Student stu = (Student)it.next();
int val = (Integer) mp.get(stu);
System.out.println(stu +","+ val);//为什么打印出来的是地址值呢?,用 System.out.println(stu.getName()+", "+stu.getAge() +", "+ val); 打印的就是学生信息了呢 求解
为什么视频教程里老师说的例子就没有toString方法 打印的就是内容呢?看视频 《黑马程序员_毕向东_Java基础视频教程第16天-06-集合(Map练习)》
}
}
}
|