You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何交换List指定索引元素?遇‘Variable expected’编译报错求解

解决List元素交换的编译错误

你的第一个写法里,this.myQueue.get(i) = temp1;编译报错「Variable expected」,核心原因是List的get()方法返回的是元素的取值,不是可被赋值的变量,Java不允许直接给方法的返回值赋值。

第二个写法只是在交换临时变量temp和temp1的值,完全没对原ListmyQueue做任何修改,自然达不到交换元素的目的。

正确实现代码

要修改List指定索引的元素,必须使用List的set(int index, E element)方法,修改后的exch方法如下:

private Comparator<T> cc;
private List<T> myQueue;
   
private void exch(int i, int j) {  // 交换索引i和j处的元素
    T temp = this.myQueue.get(i);
    this.myQueue.set(i, this.myQueue.get(j));
    this.myQueue.set(j, temp);
}

逻辑说明

  1. 先把索引i处的元素存入临时变量temp,避免被覆盖后丢失
  2. 调用set(i, ...)将索引i的位置替换为索引j的元素
  3. 调用set(j, temp)将索引j的位置替换为原索引i的元素(临时变量保存的值)

这样就能正确完成两个指定索引位置元素的交换。

内容的提问来源于stack exchange,提问作者user18984687

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 04:31:04