本帖最后由 樱木花道10 于 2013-3-23 20:40 编辑
import java.util.Collection;
import java.util.TreeMap;
/*
*需求:元素的唯一性,如果同年龄同姓名是为同一人
* 键是String,值是Student
*/
public class HashMapDemo {
public static void main(String[] args) {
// 创建集合对象
TreeMap<String, Student> hs = new TreeMap<String, Student>();
// 创建元素对象
Student s1 = new Student("张嘉译", 50);
Student s2 = new Student("刘嘉玲", 45);
Student s3 = new Student("乐嘉", 40);
Student s4 = new Student("刘嘉玲", 45);
// 添加元素
hs.put( "yl001",s1);
hs.put( "yl002",s2);
hs.put( "yl003",s3);
hs.put( "yl004",s4);
// 遍历
Collection<Student> c = hs.values();
for (Student value : c) {
//我想在这里写通过值来得到键的代码,但我不知道怎么写
//就是这里什么都不写,也得不出我要判断元素唯一性的结果
//求大神解惑...
System.out.println(value.getName() + "***" + value.getAge());
}
}
}
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|