4:Set接口
不保证元素的顺序、元素不允许重复。
没有get()方法 。
常用的实现类:
HashSet: 不能实现排序,不是线程安全的
TreeSet: 可以实现排序,不是线程安全的
排序问题:
按学号排、按成绩
java.lang.Comparable
内部排序
java.util.Comparator
外部排序
public class Student implements Comparable<Student>{
private String name;
private int score;
private String id;
public Student() {
}
public Student(String name, int score, String id) {
super();
this.name = name;
this.score = score;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public int compareTo(Student s) {
String id_=s.getId();
//按学号的升序排
//return this.id.compareTo(id_);
//按学号的降序排
return id_.compareTo(this.id);
}
}
package com.newer.demo;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
//创建Set的实例
Set<Student> stus=new HashSet<>();
Student s=new Student("张三",90,"1001");
stus.add(s);
s=new Student("李四",80,"1002");
stus.add(s);
s=new Student("王五",70,"1003");
stus.add(s);
s=new Student("王二",71,"1004");
stus.add(s);
System.out.println(stus.size());
System.out.println(stus.isEmpty());
//遍历
for(int i=0;i<stus.size();i++) {
}
//遍历两种方式:一是foreach;二是使用迭代器
for (Student student : stus) {
System.out.println("name:"+student.getName());
System.out.println("score:"+student.getScore());
System.out.println("id:"+student.getId());
System.out.println("----------------------------------------------------");
}
System.out.println("=================================================================");
//使用迭代器
Iterator<Student> its= stus.iterator();
while(its.hasNext()) {
Student st=its.next();
System.out.println("name:"+st.getName());
System.out.println("score:"+st.getScore());
System.out.println("id:"+st.getId());
System.out.println("----------------------------------------------------");
}
}
}
package com.newer.demo;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class SetDemo2 {
public static void main(String[] args) {
// 创建Set的实例:TreeSet可以实现排序
Set<Student> stus = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student arg0, Student arg1) {
int score1=arg0.getScore();
int score2=arg1.getScore();
//按成绩降序
return score2-score1;
}
});
Student s = new Student("张三", 90, "1001");
stus.add(s);
s = new Student("李四", 80, "1002");
stus.add(s);
s = new Student("王五", 70, "1003");
stus.add(s);
// 遍历两种方式:一是foreach;二是使用迭代器
for (Student student : stus) {
System.out.println("name:" + student.getName());
System.out.println("score:" + student.getScore());
System.out.println("id:" + student.getId());
System.out.println("----------------------------------------------------");
}
}
}