Set

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);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值