您的位置:首页 > 编程语言 > Java开发

Java中HashSet、TreeSet的区别

2016-05-25 21:10 731 查看
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]
third
forth
first
second
[first, forth, second, third]
first
forth
second
third
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 集合