Java中HashSet、TreeSet的区别

来源:互联网 发布:英文录音翻译软件 编辑:程序博客网 时间:2024/05/19 11:37

1、HashSet、TreeSet的区别

HashSet是使用散列表进行存储,元素无序,元素允许为null。TreeSet是使用树结构来进行存储,元素按字符串顺序排序存储,元素不允许为null。

2、简单实例

public class Test {public static void main(String[] args) {ShowHashSet();ShowTreeSet();}public static void ShowHashSet() {Set<String> sets = new HashSet<String>();sets.add("first");sets.add("second");sets.add("third");sets.add("forth");System.out.println(sets);Iterator<String> i = sets.iterator();while (i.hasNext()) {String value = i.next();System.out.println(value);}}public static void ShowTreeSet() {Set<String> sets = new TreeSet<String>();sets.add("first");sets.add("second");sets.add("third");sets.add("forth");System.out.println(sets);Iterator<String> i = sets.iterator();while (i.hasNext()) {String value = i.next();System.out.println(value);}}}

3、运行结果

[third, forth, first, second]thirdforthfirstsecond[first, forth, second, third]firstforthsecondthird

0 0
原创粉丝点击