Java List相关用法

本文详细介绍了Java中List的subList方法的使用,Queue和Deque接口的区别及其实现方式,包括它们的主要方法和应用实例。同时,还探讨了List的常用算法,如排序方法及其背后的Comparable和Comparator接口的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值