TEST
来源:互联网 发布:域名已被注册了怎么办 编辑:程序博客网 时间:2024/05/29 17:55
Set 集合
元素无序,元素不可重复,存入和取出的顺序不一定相同。
Table of Contents
- 1 HashSet
- 2 TreeSet
1 HashSet
底层数据结构是哈希表。Java中打印对象得到的结果是对象的哈希值,例如
class class demo { } class HashSet { public static void main(String[] args) { demo d1 = new demo(); demo d2 = new demo(); System.out.println(d1); System.out.println(d2); } }
这段代码的结果是:
HashSet根据对象在内存中的地址值大小存放对象,若多个对象地址值相同,但是属于不同对象,则在该地址值下顺延。
2 TreeSet
TreeSet会对存入的对象排序。例如存入的是字符串,则按照字符在字母表中的先后顺序排列。如存入的对象是数字,怎按照数字大小排序。
在往TreeSet类中存入自定义对象时容易出现错误。例如如下代码:
1: import java.util.*; 2: 3: class Student 4: { 5: private int age; 6: private String name; 7: 8: Student(String name, int age) 9: {10: this.age = age;11: this.name = name;12: }13: }14: 15: class TreeSetDemo16: {17: public static void main(String[] args)18: {19: TreeSet ts = new TreeSet();20: 21: ts.add(new Student("Tom", 22));22: ts.add(new Student("Jim", 20));23: ts.add(new Student("Bob", 24));24: 25: Iterator it = ts.iterator();26: while(it.hasNext())27: System.out.println(it.next());28: }29: }
这段代码可以通过编译,但是在运行时会出现如下错误提示:
出现上面错误提示的原因是TreeSet集合会对存入的对象排序,因此要求存入的对象具有可比性,即要求对象所属的类实现了 java.lang 中的Comparable 接口。
Date: 2013-01-22T08:59+0800
Org version 7.9.3a with Emacs version 23
Validate XHTML 1.0- test
- test
- test
- test
- test
- test
- test
- Test
- test
- Test
- test
- test
- test
- test
- test
- test
- test
- Test
- <command-line>:0:0: error: "_FORTIFY_SOURCE" redefined [-Werror]
- awk用法 Linux
- IO流
- Discuz! X lang 函数参数详解
- android 休眠唤醒机制分析(一)
- TEST
- hdu2923
- android中的左右滑屏实现
- printf()格式化输出详解
- android 休眠唤醒机制分析(二)
- ASP.NET MVC下保存输入敏感内容时去掉验证
- 正则表达式
- 东子破解的java设计模式状态模式
- 黑马程序员——java中的线程