集合練習(xí) 練習(xí):每一個學(xué)生Student都有一個對應(yīng)的歸屬地定義為String類型。學(xué)生屬性:姓名,年齡 注意:姓名和年齡相同的視為同一個學(xué)生。保證學(xué)生的唯一性。 1、描述學(xué)生。 2、定義Map容器,將學(xué)生作為鍵,地址作為值存入集合中。 3、獲取Map中的元素并進(jìn)行排序。
package com.rf.xs.map;
public class Student implements Comparable<Student> {
private String name;
private int 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;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Student o) {
// TODO Auto-generated method stub
if (o instanceof Student) {
Student stu = (Student) o;
int num = this.name.compareTo(stu.name);
if (num == 0) {
if (this.age > stu.age)
return 1;
if (this.age == stu.age) {
return 0;
}
return -1;
}
return num;
}
return 0;
}
}
package com.rf.xs.map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Stu {
public static void main(String[] args) {
Student s1 = new Student("b", 15);
Student s2 = new Student("a", 16);
Student s3 = new Student("c", 16);
HashMap<Student, String> m = new HashMap<Student, String>();
m.put(s1, "成都");
m.put(s3, "上海");
m.put(s2, "北京");
//Set<Student> ts =new TreeSet<Student>(set);
Set<Student> set =m.keySet();
Set<Student> ts =new TreeSet<Student>();
ts.addAll(set);
Iterator<Student> it = ts.iterator();
while(it.hasNext()){
Student stu = it.next();
System.out.println(stu+" "+m.get(stu));
}
}
}
浙公網(wǎng)安備 33010602011771號