package com .foot .class 02
import java.util .Comparator
import java.util .HashSet
import java.util .Set
import java.util .TreeSet
public final class HashTreeSet {
public static void main(String[] args) {
System.out .println ("*******************************************HashSet无序存放******************************************" )
Set <Student> hashSet = new HashSet<Student>()
hashSet.add (new Student(1 , "张三" , "S1002" , 12 ))
hashSet.add (new Student(2 , "朱琪" , "S1006" , 5 ))
hashSet.add (new Student(3 , "赵盼" , "S1021" , 32 ))
hashSet.add (new Student(4 , "秦静" , "S2010" , 79 ))
hashSet.add (new Student(5 , "月英" , "S3056" , 23 ))
for (Student student : hashSet) {
System.out .println ("id:" + student.getId () + "--姓名:" + student.getName () + "--学号:" + student.getNum () + "--年龄:" + student.getAge ())
}
System.out .println ("*******************************************TreeSet年龄升序存放******************************************" )
Set <Student> treeSet = new TreeSet<Student>(new MyComparator())
treeSet.add (new Student(1 , "张三" , "S1002" , 12 ))
treeSet.add (new Student(2 , "朱琪" , "S1006" , 5 ))
treeSet.add (new Student(3 , "赵盼" , "S1021" , 32 ))
treeSet.add (new Student(4 , "秦静" , "S2010" , 79 ))
treeSet.add (new Student(5 , "月英" , "S3056" , 23 ))
for (Student student : treeSet) {
System.out .println ("id:" + student.getId () + "--姓名:" + student.getName () + "--学号:" + student.getNum () + "--年龄:" + student.getAge ())
}
}
}
class MyComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
//返回值如果乘以-1 ,则将进行降序排列
//这里还可以定义规则按照字母或汉字进行排列
return o1.getAge () - o2.getAge ()
}
}
package com.foot.class02;
public class Student {
private int id;
private String name;
private String num;
private int age;
public Student () {
}
public Student (int id, String name, String num, int age) {
this .id = id;
this .name = name;
this .num = num;
this .age = age;
}
public int getId () {
return id;
}
public void setId (int id) {
this .id = id;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public String getNum () {
return num;
}
public void setNum (String num) {
this .num = num;
}
public int getAge () {
return age;
}
public void setAge (int age) {
this .age = age;
}
}