要解决这个问题,你可以创建一个新的类来扩展 ArrayList,然后在该类中定义一个名为 change 的方法,该方法接受两个 Bar 对象作为参数。下面是一个示例代码:
import java.util.ArrayList;
public class BarArrayList extends ArrayList {
public void change(Bar oldBar, Bar newBar) {
int index = this.indexOf(oldBar);
if (index != -1) {
this.set(index, newBar);
}
}
}
在上面的代码中,我们创建了一个名为 BarArrayList 的类,它继承自 ArrayList
现在你可以使用 BarArrayList 类来创建一个 ArrayList 对象,并使用 change 方法来修改其中的元素。下面是一个示例代码:
Bar bar1 = new Bar();
Bar bar2 = new Bar();
Bar bar3 = new Bar();
BarArrayList barList = new BarArrayList();
barList.add(bar1);
barList.add(bar2);
barList.add(bar3);
System.out.println("Before change:");
for (Bar bar : barList) {
System.out.println(bar);
}
Bar newBar = new Bar();
barList.change(bar2, newBar);
System.out.println("After change:");
for (Bar bar : barList) {
System.out.println(bar);
}
在上面的代码中,我们创建了三个 Bar 对象并将它们添加到 BarArrayList 对象中。然后我们使用 change 方法将 bar2 替换为一个新的 Bar 对象。最后我们遍历 BarArrayList 对象并打印每个元素,以验证修改是否成功。
请注意,为了运行上面的代码,你需要定义一个名为 Bar 的类,并在其中实现 toString 方法,以便能够打印 Bar 对象的内容。
上一篇:ArrayList: 当你有多个setter时如何使用arraylist.set
下一篇:ArrayList<Course>类型中的方法add(Course,Object[],int)对参数[Java]不适用