Java 数据结构之 List接口中的replaceAll() ---UnaryOperator

本文深入解析了Java中List接口的replaceAll方法,通过实例展示了如何使用UnaryOperator接口替换List中的元素,解释了其在ArrayList中的实现细节,并提供了代码示例。

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

default void replaceAll(UnaryOperator<E> operator)
对于该方法,Java jdk1.8手册里是这么描述的 :用函数接口的返回结果替代原list中的值.

list 接口中的源码

default void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final ListIterator<E> li = this.listIterator();
    while (li.hasNext()) {
        li.set(operator.apply(li.next()));
    }
}

arraylist 中的源码

public void replaceAll(UnaryOperator<E> operator) {
    Objects.requireNonNull(operator);
    final int expectedModCount = modCount;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        elementData[i] = operator.apply((E) elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
 
其中,UnaryOperator<E> 这个类型,中文翻译了一下,是一元运算符的意思。
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {

    /**
     * Returns a unary operator that always returns its input argument.
     *
     * @param <T> the type of the input and output of the operator
     * @return a unary operator that always returns its input argument
     */
    static <T> UnaryOperator<T> identity() {
        return t -> t;
    }
}

@FunctionalInterface这是个函数式接口注解,并且只能用一元操作符

List<Integer> numList = new ArrayList<>();
numList.add(1);
numList.add(2);
numList.add(3);
 
//这里将函数改成了t -> t + 1
numList.replaceAll(t -> t + 1);
 
for (int i = 0; i < numList.size(); i++) {
    System.out.println(numList.get(i));
}
运行结果:

2   3   4

类似于这样的输入函数,都可以
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值