JAVA集合框架:[23]map案例四

class  Person implements Comparable{

private int age;

private String name;

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Override

public boolean equals(Object arg0) {

// TODO Auto-generated method stub

if(this == arg0)

return true;

if(!(arg0 instanceof Person))

throw new ClassCastException("類型錯誤!");

Person p = (Person)arg0;

return this.name.equals(p.name) && this.age== p.age;

}

@Override

public int hashCode() {

// TODO Auto-generated method stub

return name.hashCode()+age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Person(int age, String name) {

super();

this.age = age;

this.name = name;

}

public Person() {

super();

// TODO Auto-generated constructor stub

}

@Override

public int compareTo(Object arg0) {

// TODO Auto-generated method stub

Person person= (Person)arg0;

int temp=this.age-person.age;

return temp==0?this.name.compareTo(person.name):temp;

}

}

本文內容整理自網絡, 文中所有觀點看法不代表淘大白的立場