Arraylist – 设置/添加方法用法 – Java

我有一个整数的Arraylist。 我的要求是确定arraylist是否存在于指定索引处的元素。如果是,则应将值设置为该索引(使用set方法),否则应将值添加到该索引位置(使用add方法)

在我的java代码中找到处理上述条件有点困难。请帮忙。

这是我到目前为止所拥有的:

  ArrayList tempArray = new ArrayList(); int counter = 0; int tempValue = 0; For LOOP - if (//certain conditions are satisfied){ tempValue = calculateNewValue(); tempArray.add(counter, tempValue); //Need some logic here to determine if its a set or add method to be used } if (//some other conditions are satisfied){ counter++; } end For LOOP 

你不需要循环。 ArrayList 有一个indexOf方法,可用于获取对象的第一个出现。 一定要正确实现equals

ArrayList 还有一个add方法,允许您设置插入元素的索引。 或者一个set方法 ,可能是你想要的(取决于你想要做什么)

其他答案已提供有关使用列表中可用的indexOf方法的信息。 但是,只需添加一些关于java中ArrayList中“add”和“set”之间差异的信息。

来自javadocs –

add(index, value)方法 – 将指定元素插入此列表中的指定位置。 将当前位于该位置的元素(如果有)和任何后续元素移位到右侧(将其添加到其索引中)。

set(index, value) – 用指定的元素替换此列表中指定位置的元素。

因此,使用add()而不是set() increases your list size 。 无论您是否需要此行为,您都应该考虑这一点。

你想要的是Map而不是List

如果counter大于List.size()会怎么样? 您是否根据需要添加了多少元素?

以下是确定在数组中插入或替换值的位置的逻辑。

 if (tempArray.indexOf(tempValue) < 0) { tempArray.add(counter, tempValue); } else { tempArray.set(counter, tempValue); } 

PS最好将counter重命名为index

set方法用新元素替换指定位置的元素。 但是在add(position,element)中会将元素添加到指定位置,并将现有元素移动到数组的右侧。

 ArrayList al = new ArrayList(); al.add("a"); al.add(1, "b"); System.out.println(al); al.set(0, "c"); System.out.println(al); al.add(0, "d"); System.out.println(al); 

—————输出———————————- —

[a,b]

[c,b]

[d,c,b]

ArrayList具有contains(Object o)方法 ,“如果列表包含指定的元素,则返回true”,同样可以确定要使用的方法, add()set()