集合练习 练习:每一个学生Student都有一个对应的归属地定义为String类型。学生属性:姓名,年龄 注意:姓名和年龄相同的视为同一个学生。保证学生的唯一性。 1、描述学生。 2、定义Map容器,将学生作为键,地址作为值存入集合中。 3、获取Map中的元素并进行排序。

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));

}

 

 

}

}

原文地址:https://www.cnblogs.com/xiaoshuaidiboke/p/7196959.html