list取第一个元素_数据结构 - List 接口

c27079fbe160444e4cdf127701469c61.png

简介

List接口继承自Collection接口,是Collection三大延伸接口之一。List中的元素都是有序的,并且都支持用索引访问。同时List中的元素允许重复。

public interface List<E> extends Collection<E>

方法

List中Collection接口中大部分方法又重新定义了一遍,当然也有定义自己特有的方法,这里重要讲特有方法,其他方法请参考上一篇Collection接口。

// 替换所有 UnaryOperator会另开一篇讲解
default void replaceAll(UnaryOperator<E> operator) {
    
    Objects.requireNonNull(operator);
    final ListIterator<E> li = this.listIterator();
    while (li.hasNext()) {
    
        li.set(operator.apply(li.next()));
    }
}
// 排序
@SuppressWarnings({
    "unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
    
    Object[] a = this.toArray();
    // 主要使用 Arrays.sort 进行排序
    Arrays.sort(a, (Comparator) c);
    // 迭代原集合
    ListIterator<E> i = this.listIterator();
    // 遍历新数组
    for (Object e : a) {
    
        i.next();
        // 使原集合中元素位置跟新数组中一致,这里直接替换
        i.set((E) e);
    }
}
// 根据索引查找
E get(int index);
// 根据索引设置元素
E set(int index, E element);
// 根据索引位置添加
void add(int index, E element);
// 根据索引位置删除
E remove(int index);
// 获取元素在集合中的第一个索引
int indexOf(Object o);
// 获取元素在集合中最后一个索引
int lastIndexOf(Object o);
// 获取一个列表迭代器
ListIterator<E> listIterator();
// 从某个位置开始构建迭代器
ListIterator<E> listIterator(int index);
// 截取某一段构建集合
List<E> subList(int fromIndex, int toIndex);

相对于Collection接口来说,

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值