ArrayList的 - 设置/ add方法的使用 - Java的 [英] Arraylist - Set/ add method usage - Java
问题描述
我有一个整数的ArrayList。
我的要求是,以确定是否ArrayList中曾在指定index.If YES,那么值应设置为现有的索引(使用设置
法)的元素,否则一值应该(用添加
法)被添加到索引位置
查找有点难以处理在我的Java code.请帮助上述条件。
下面是我到目前为止有:
的ArrayList<整数GT; tempArray =新的ArrayList<整数GT;();
INT计数器= 0;
INT tempValue = 0;
FOR循环 -
如果(//某些条件得到满足){ tempValue = calculateNewValue();
tempArray.add(计数器,tempValue); //需要一些逻辑,在这里,以确定其是否一组或添加方法中使用
}
如果(//一些其他条件都满足){
反++;
}
结束FOR循环
您不需要循环。 的ArrayList
有你可以用它来获取对象的第一次出现的的indexOf 方法。一定要落实等于
正常。
的ArrayList
的也有一个添加
方法,它允许您设置该元素插入索引。 或一组方法,这可能是你想要的(取决于正是你正在尝试做的)
I have an Arraylist of integers.
My requirement is to determine if the arraylist HAS an element existing at the specified index.If YES, then a value should be set to that index (using set
method), else a value should be added to that index location(using add
method)
Finding it a bit difficult to handle the above condition in my java code.Please help.
Here's what I have so far:
ArrayList<Integer> tempArray = new ArrayList<Integer>();
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
You don't need to loop. ArrayList
has an indexOf method you can use to get the first occurence of the object. Be sure to implement equals
correctly.
ArrayList
also has an add
method that allows you to set the index at which the element is inserted. Or a set method, that might be what you want (depending on exactly what you are trying to do)
这篇关于ArrayList的 - 设置/ add方法的使用 - Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!