Comparable:一般的javabean都会实现,用于排序。如果开发者add进入一个Collection的对象想要Collections的sort方法帮你自动进行排序的话,那么这个对象必须实现Comparable接口。
Comparator:外部比较器,使用场景:
1、类的设计师没有考虑到比较问题而没有实现Comparable,可以通过Comparator来实现排序而不必改变对象本身
2、可以使用多种排序标准,比如升序、降序等
public class CompareTest {
public static void main(String args[]) {
Domain d1 = new Domain("enzo",12);
Domain d2 = new Domain("peekaboo",12);
Domain d3 = new Domain("bamboo",15);
Domain d4 = new Domain("carter",16);
System.out.println(d1.compareTo(d2));
DominComparator comparator = new DominComparator();
System.out.println( comparator.compare(d1, d3) );
TreeMap<Domain, String> map = new TreeMap<Domain, String>(comparator);
map.put(d1,"d1");
map.put(d2,"d2");
map.put(d3,"d3");
map.put(d4,"d4");
System.out.println(map.firstKey());
System.out.println(map.lastKey());
Set<Entry<Domain, String>> set = map.entrySet();
Iterator<Entry<Domain, String>> it = set.iterator();
while(it.hasNext()) {
Entry<Domain, String> entry = it.next();
System.out.println(entry.getKey()+" -- "+entry.getValue());
}
}
}
//外比较器,自定义比较规则
class DominComparator implements Comparator<Domain> {
public int compare(Domain o1, Domain o2) {
if(o1.getName().compareToIgnoreCase(o2.getName())>0) {
return 1;
} else if(o1.getName().compareToIgnoreCase(o2.getName())<0) {
return -1;
} else {
if(o1.getAge()-o2.getAge()>0) {
return 1;
} else if(o1.getAge()-o2.getAge()<0) {
return -1;
} else {
return 0;
}
}
}
}
//内比较器,一般的Javabean都要实现该接口,然后就可以添加进排序的集合类
class Domain implements Comparable<Domain>{
private String name;
private int age;
public Domain(String name,int age) {
this.name = name;
this.age = age;
}
//省略getter、setter
public int compareTo(Domain p) {
if(this.getName().compareTo(p.getName())>0) {
return 1;
} else if(this.getName().compareTo(p.getName())<0) {
return -1;
} else { //当两个人的姓名相同时,对年龄进行排序
if(this.getAge()-p.getAge()>0) {
return 1;
} else if(this.getAge()-p.getAge()<0) {
return -1;
} else {
return 0;
}
}
}
@Override
public String toString() {
return "Domain [name=" + name + ", age=" + age + "]";
}
}
Collection是集合接口
|————Set子接口:无序,不允许重复。
|————List子接口:有序,可以有重复元素。
Set
|————HashSet:以哈希表的形式存放元素,插入删除速度很快。
|————TreeSet:以二叉树排序形式存放元素,有序的获取元素。
List
|————ArrayList:动态数组,非同步
|————LinkedList:链表、队列、堆栈,非同步。
|————Vector:动态数组,同步的。子类:———– |Stack :栈,同步的。
|
TreeMap和HashMap:
“集合框架”提供两种常规的 Map实现:HashMap和TreeMap (TreeMap实现SortedMap接口)。
在Map 中插入、删除和定位元素,HashMap 是最好的选择。但如果您要按自然顺序或自定义
顺序遍历键,那么TreeMap会更好。使用HashMap要求添加的键类明确定义了hashCode()和
equals()的实现。
HashMap和HashTable:
1). HashMap支持null值和一个null键;HashTable不支持;
2 ) . HashTable是同步的;HashMap可以通过Collections.synchronizedMap(hashMap)达到同步。
fail-fast:快速失败机制(一种错误检测机制),指程序在对集合使用迭代器迭代时,如果有操作对集合结构进行改变,则会尽可能地抛出异常。可以简单地认为java.util包下的集合类都是快速失败机制。
safe-fase:安全失败机制,指程序在对集合使用迭代器迭代时,即使有操作对集合结构进行改变,也不会抛出异常。因为对该集合进行迭代时,在底层对原集合进行了拷贝。可以简单地认为java.util.concurrent(并发包)包下的集合类都是安全失败机制。