문제

I need to add an outside number to EVERY number in an ArrayList. I've looked for 2 days trying to find a similar answer and found nothing.

ArrayList<Integer> list = new ArrayList<Integer>();
  list.add(12);
  list.add(45);
  list.add(23);
  list.add(47);
  list.add(13);

public static void modifyList(ArrayList<Integer> theList, int value)
{
  for (int i = 0; i < theList.size(); i++)
  {
    theList.add(theList[i],value);
  }
}

I've tried various combinations of the add feature for ArrayList but there is always a different error and i'm starting to go crazy

도움이 되었습니까?

해결책

The logic will be as below :

for (int i = 0; i < theList.size(); i++) {
            int oldValue = theList.get(i);
            int newValue = oldValue + value;
            theList.set(i, newValue);
        }

다른 팁

You can use the set method.

Arraylist.set(index,value);

Getting the i value from an arraylist works using the get method.

You have:

theList.add(theList[i], value);

It should probably be:

theList.add(theList.get(i));

If you want to change the i element in the list, then you can use the set method.

theList.set(i, value);
int a = theList.get(i) + your_addition;

theList.set(i, a);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top