天天看点

JAVA语言之Set

一、Set和List的区别

List中可以存在相同的元素,而Set不可以。基于这个特性,Set可以被用来实现去重,可作为Map的键

二、常见的Set

常见的Set有HashSet、LinkedHashSet、TreeSet

这些具体的实现类都继承了Set接口,实现了插入、删除、求长度、判断是否为空等方法

System.out.println(set.add(new grade("zhangsan",85,88)));
System.out.println(set.add(new grade("zhangsan",85,88)));
           

输出

true
false
           

当试图插入相同元素时,第二次插入是无效的

下面给出这三种具体实现类的区别

HastSet 

不能保证元素的排列顺序,顺序有可能发生变化

集合元素可以是null,但只能放入一个null

当向HashSet结合中存入一个元素时,HashSet会调用该对象的hashCode()方法来得到该对象的hashCode值,然后根据 hashCode值来决定该对象在HashSet中存储位置。

也就是说,HashSet的位置是由HashCode决定的

LinkedHashSet 

和HashSet的区别在于,LinkedHashSet的元素是按照插入的顺序输出的

public static void main(String[] args) {
        LinkedHashSet set = new LinkedHashSet();
        ConstructSet(set);
        HashSet hashSet = new HashSet();
        ConstructSet(hashSet);
    }

    public static void ConstructSet(Set set){
        set.add(new grade("zhangsan",85,88));
        set.add(new grade("lisi",80,87));
        set.add(new grade("wangwu",70,98));
        set.add(new grade("zhaoliu",65,100));
        Iterator it = set.iterator();
        while (it.hasNext()){
            System.out.println(it.next().toString());
        }
    }
           

输出:

name = zhangsan   age =  85   math =  88
name = lisi   age =  80   math =  87
name = wangwu   age =  70   math =  98
name = zhaoliu   age =  65   math =  100
name = wangwu   age =  70   math =  98
name = zhangsan   age =  85   math =  88
name = zhaoliu   age =  65   math =  100
name = lisi   age =  80   math =  87
           

TreeSet

和HashSet不同,TreeSet可以开发人员指定排序方式