1. subList
List的subList用于获取子List,由于二者公用相同的存储空间,所以,对subList的操作,会影响到List。
List<E> subList(int fromindex, toindex);
//两参数分别到要获取对象位置的上下标,包括上标不包括下标志。
如:
List<Integer> subList = list.subList(2,10);
2. Queue接口
使用LinkedList来实现Queue接口。
Queue(队列):具有先进先出存储结构。
Queen<String> quene = new LinkedList<String>();
该接口常用的方法有:
//讲一个对象添加至队尾
boolean affer(E, e);
//从队首删除并返回一个元素
E poll();
//返回队首的元素,但不删除
E peek();
3. Deque接口
Deque接口为Queue的子接口,为双向队列。
使用LinkedList实现Dueue接口。
也可将其设定为单进单出,这样形成另一种存储结构,栈:后进先出。进栈push,出栈pop。
String str = "ABCDEFG";
Dueue<Charactor> stack = new LinkedList<Charactor>();
for(int i=0; i<str.length(); i++){
stack.push(str.charAt(i));
}
System.out.println(stack);
///输出结果:[GFEDCBA]
可用peek判断栈是否为空。当栈为空时,返回null。
while(stack.peek()!=null){
System.out.println(stack.pop());
}
//输出结果:GFEDCBA
4. List常用算法
Comparable接口:用于比较对象的大小关系。
//接口定义:
public interface Compatable<T>{
public int conpataTo(T o);
}
//接口实现
//Point类实现该接口
public class Point inplements Comparable<Point>{
private x; private y;
//根据原点距离判断大小
public int comparaTo(T o){
int r = x*x + y*y;
int r1 = o.x*o.x + o.y*o.y;
return r-r1;
}
public boolean equals(Object obj){
if(obj instanceof Point){
Point p = (Point)obj;
return p.x==x && p.y==y;
}
else
return false;
}
}
注意:在编写comparaTo方法后,也要编写其对应的equals方法。使得二者对应。
5. Collections.sort方法
对集合元素排序,但是集合对象需要实现Comparable接口。
因为sort方法是调用Comparable接口中的comparaTo方法进行比较。
例:
//其中,Point类已经实现Comparable接口
List<Point> list = new ArrayList<Point>();
list.add((1,2));
list.add((2,3));
list.add((1,5));
Collections.sort(list);
System.out.println(list);
//输出结果:[(1,2),(2,3),(1,5)]
6. Comparator接口
一旦Java实现Comparator接口,其比较逻辑就被确定,如果要临时改变比较规则,则采用Comparator接口回调的方式。
// 接口定义
public interface Comparator<T>{
public int compara(T o1, T o2);
}
Comparator回调
List<Point> list = new ArrayList<Point>();
list.add((1,2));
list.add((2,3));
list.add((3,5));
Collections.sort(list,
new Comparator<Point>(){
//compara方法实现比较x坐标的大小
public int compara(Point o1, Point o2){
return o1.getX() - o2,getX();
}
});
System.out.println(list);
//输出结果:[(1,2),(2,3),(3,5)]