1.ArraList和linkedList的区别及优缺点
1).ArrayList是实现了基于动态数组的数据结构,LinkedList是基于链表的数据结构
2).对于随机访问get和set,ArrayList优于LinkedList。因为,LinkedList要移动指针。
3).对于新增和删除操作add和remove,linkedlist比较占优势。因为,ArrayList要移动数据。这一点要看实际情况的,若只对单条数据插入或删除,ArrayList的速度反而优于linkeList。但若是要批量的随机插入或删除数据,linkedlist的速度大大优于Arraylist。因为ArrayList每插入一条数据,要移动插入点及之后的所有数据。
Collections类
1)Collections类所提供的方法均为静态方法(static),可以直接通过“类名.方法()”的形式调用
Comparable:根据元素的自然顺序返回指定集合的最小元素。
Comparator:根据指定的比较器产生的顺序,返回指定的集合的最小元素。
2).Comparable与Comparator的区别
omparable & Comparator 都是用来实现集合中元素的比较、排序的,只是 Comparable 是在集合内部定义的方法实现的排序,Comparator 是在集合外部实现的排序,所以,如想实现排序,就需要在集合外定义 Comparator 接口的方法或在集合内实现 Comparable 接口的方法。 Comparator位于包java.util下,而Comparable位于包 java.lang下
Comparable 是一个对象本身就已经支持自比较所需要实现的接口(如 String、Integer 自己就可以完成比较大小操作,已经实现了Comparable接口)
自定义的类要在加入list容器中后能够排序,可以实现Comparable接口,在用Collections类的sort方法排序时,如果不指定Comparator,那么就以自然顺序排序,如API所说:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface 这里的自然顺序就是实现Comparable接口设定的排序方式。
而 Comparator 是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足你的要求时,你可以写一个比较器来完成两个对象之间大小的比较。
可以说一个是自已完成比较,一个是外部程序实现比较的差别而已。
用 Comparator 是策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。
比如:你想对整数采用绝对值大小来排序,Integer 是不符合要求的,你不需要去修改 Integer 类(实际上你也不能这么做)去改变它的排序行为,只要使用一个实现了 Comparator 接口的对象来实现控制它的排序就行了。