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
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对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树