Set笔记

来源:互联网 发布:易订货源码下载 编辑:程序博客网 时间:2024/06/08 12:35

import com.hephec01;

public class HashSetTest{

public static void main(String[] args){

Random rand=new Random();

Set<String> hash=new HashSet<String>();

for(int i=0;i<10000;i++){

hash.add(rand.nextInt(30));

System.out.println(hash);

}

}

}

//HashSet使用的是散列技术

//测试输出数据并没有10000个

import com.hephec02;

public class TreeSetTest{

public static void main(String[] args){

Random rand=new Random();

Set<String> tree=new TreeSet<String>();

for(int i=0;i<10000;i++){

tree.add(rand.nextInt(30));

System.out.println(hash);

}

}

}

//TreeSet将元素存储在红黑树中

//测试输出数据并没有10000个


Set(interface)

存入Set每个元素必须是唯一的,因为Set不保存重复元素,加入Set元素必须重定义equals()方法以此确保对象的唯一性,SetCollection有完全一样的接口,Set接口不保证维护元素的次序

HashSet

为快速查找而设计的Set,存入HashSet的元素必须定义hashCode()

TreeSet

保持次序的Set,底层为树结构,使用它可以从Set中提取有序的序列,元素必须实现Comparable接口

LinkedHashSet

具有HashSet的查询速度,且内部使用链表维护元素的顺序(插入的次序)于是在使用迭代器遍历Set时,结果会按照元素的插入次序显示,元素也必须定义hashCode()方法


0 0