不同数据结构判断元素是否相同的比较原理 arraylist equals hashset hashCode equals treeset 自定义比较器的compare的return 0 或是元素自身的compareTo的rutren 0 treeset的看下面的例子 class TreeSetDemo3 { public static void main(String[] args) { TreeSet ts = new TreeSet(new StudentComparatorByName());//比较器 //TreeSet ts = new TreeSet();//元素自身 ts.add(new Student("lisi0",30)); ts.add(new Student("lisixx",29)); ts.add(new Student("lisi9",29)); ts.add(new Student("lisi8",38)); ts.add(new Student("lisixx",29)); ts.add(new Student("lisi4",14)); //ts.add(new Student(39)); ts.add(new Student("lisi7",27)); System.out.println(ts); } } class StudentComparatorByName implements Comparator { public int compare(Object o1,Object o2) { Student s1 = (Student)o1; Student s2 = (Student)o2; int num = s1.getName().compareTo(s2.getName()); return num==0?new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())):num; } } //同姓名同年龄的学生视为同一个学生。按照学生的年龄排序。 class Student implements Comparable { private int age; private String name; Student(String name,int age) { this.age = age; this.name = name; } public int compareTo(Object obj) { Student stu = (Student)obj; int num = new Integer(this.age).compareTo(new Integer(stu.age)); return num==0?this.name.compareTo(stu.name):num; /* if(this.age>stu.age) return 1; if(this.age==stu.age) return this.name.compareTo(stu.name); return -1; */ /**/ } public int getAge() { return age; } public String getName() { return name; } public String toString() { return name+"::"+age; } } 1:对象不能被多个线程同时操作,那么此对象线程不安全。 hashMap线程不安全,hashTable对象线程安全,但多个线程分别调用hashTable的iterator()方法,得到Iterator对象后, 不再支持其他线程更改Iterator对象结构。 2:ArrayList不是线程安全的,如果想在并发中实现线程安全,可以使用CopyOnWriteArrayList类。
不同数据结构的比较原理
原创
©著作权归作者所有:来自51CTO博客作者初级菜鸟牛的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:模板设计模式
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
【数据结构】特殊矩阵的压缩存储
【数据结构】第三章——栈、队列与数组详细介绍特殊矩阵的压缩存储……
数据结构 C语言 矩阵 压缩存储 数组 -
常用数据结构的原理
不同的数据结构适用于不同的应用场景,因此了解各种数据结构的原理对于编写高效的程序至关重要。本文将介
数据结构 原力计划 Java 链表