1.TreeSet
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
public class Set1 {
public static void main(String[] args) {
//范型的写法
Set<Account> set=new TreeSet<Account>();//1.存入的元素必须自然配许,即要实现Comparable接口 2.去重,通过compareTo判断重复
set.add(new Account(1,"xy"));
set.add(new Account(2,"xz"));
set.add(new Account(3,"xq"));
//set.add(new Student()) 用别的类型会自动报错
//存重复
set.add(new Account(1,"xy"));
System.out.println(set.size());
Iterator ite= set.iterator();
while (ite.hasNext()){
Object o=ite.next();
//加范型以后不需要再用这段代码判断
// if(o instanceof Account){
// Account p=(Account)o;
// System.out.println(o);
// }
System.out.println(o);
}
}
}
class Account implements Comparable{
private int id;
private String name;
@Override
public int compareTo(Object o) {
if(o==null){
throw new RuntimeException("为空");
}
if(o instanceof Account){
Account a=(Account)o;
if(this.id==a.id){
return this.name.compareTo(this.name);
}
return this.id-a.id;
}else {
throw new RuntimeException("类型不正确");
}
}
public Account(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Account account = (Account) o;
return id == account.id &&
Objects.equals(name, account.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
2.HashSet
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Set2 {
public static void main(String[] args) {
Set set=new HashSet();// 1.无序 2.通过equals和Hashcode判断重复
set.add(new Account(1,"xy"));
set.add(new Account(2,"xz"));
set.add(new Account(3,"xq"));
//存重复
set.add(new Account(1,"xy"));
System.out.println(set.size());
Iterator ite= set.iterator();
while (ite.hasNext()){
Object o=ite.next();
if(o instanceof Account){
Account p=(Account)o;
System.out.println(o);
}
}
}
}