java中的Set有三种常用的实现方式:
1,,HashSet : HashSet将数据存储哈希表中,性能最佳。(无序)
2,TreeSet: TreeSet将数据存储在红黑树中,数据的顺序依据数据的值。(有序)
3,LinkedHashSet: LinkedHashSet中的数据存储在哈希表中,同时被链表贯穿着。它的顺序是按照插入的顺序。(有序)
package com.robert.test1;
import java.util.HashSet;
import java.util.Set;
public class HashSetTest {
public static void main(String[] args) {
Set<String> peoples = new HashSet<String>();
peoples.add("zhangsan");
peoples.add("lisi");
peoples.add("wangwu");
peoples.add("laowu");
System.out.println(peoples);
}
}
输出结果:[wangwu, laowu, lisi, zhangsan]
package com.robert.test1;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetTest {
public static void main(String args[])
{
Set persons = new TreeSet();
persons.add("green");
persons.add("linda");
persons.add("ada");
persons.add("mike");
persons.add("bread");
System.out.println(persons);
}
}
输出结果:[ada, bread, green, linda, mike]
package com.robert.test1;
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetTest {
public static void main(String[] args) {
Set persons = new LinkedHashSet();
persons.add("green");
persons.add("linda");
persons.add("ada");
persons.add("mike");
persons.add("bread");
System.out.println(persons);
}
}
输出结果:[green, linda, ada, mike, bread]