Set

本文介绍了一个Java程序示例,展示了如何使用泛型填充不同类型的Set集合,并通过自定义类实现equals、hashCode及compareTo方法来确保元素的正确存储与比较。同时,文章提供了HashSet、LinkedHashSet及TreeSet的用法示例。
import java.util.*;

class SetType{
    int i;
    public SetType(int n){ this.i = n;}
    public boolean equals(Object o){
        return o instanceof SetType && (this.i == ((SetType)o).i);
    }
    @Override
    public String toString() {
        return Integer.toString(i);
    }
    
}
class HashType extends SetType{
    public HashType(int n) {super(n);}
    public int hashCode(){return i;}
}
class TreeType extends SetType implements Comparable<TreeType>{
    public TreeType(int n){super(n);}
    
    public int compareTo(TreeType o){
        return (o.i<i?-1: (o.i ==i ?0:1));
}
}

public class TypesForSets {
    static <T> Set<T>  fill(Set<T> set,Class<T> type)
    {
        try{
            for(int i=0;i<10;i++){
                //下面代码什么鬼?
                set.add(type.getConstructor(int.class).newInstance(i));
            }
        }catch(Exception e){
            throw new RuntimeException(e);
        }
        
        return set;
        
    }
    static <T> void test(Set<T> set,Class<T> type ){
        fill(set,type);
        fill(set,type); //try to add duplicates
        fill(set,type);
        System.out.println(set);
    }
    
    public static void main(String[] args) {
        //test(new HashSet<HashType>(),HashType.class);
        //test(new LinkedHashSet<HashType>(),HashType.class);
        //test(new TreeSet<TreeType>(),TreeType.class);
        
        //Things that don't work:
        //test(new HashSet<SetType>(),HashType.class);
        
        Set<String> set = new LinkedHashSet<String>();
        set.add("Bob");
        set.add("Allen");
        set.add("Carb");
        
        System.out.println(set);
        
    }

}

 

转载于:https://www.cnblogs.com/vector11248/p/7765309.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值