1

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

JessNicole27
  • 63
  • 1
  • 7
  • 1
    I don't understand what you're trying to do. Can you give an input/output example? – Hugo Sousa Feb 15 '14 at 19:35
  • @HugoSousa It should be displayed as: LIST = 12, 45, 23, 47, 13; then with the modifyList method it should add any declared integer to each element in the array. If i used 1 it should change to: LIST = 13, 46, 23, 48, 14 – JessNicole27 Feb 15 '14 at 19:36

4 Answers4

0

You can use the set method.

Arraylist.set(index,value);
Junior
  • 17
  • 1
  • 6
0

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);
Chronicle
  • 1,565
  • 3
  • 22
  • 28
0
int a = theList.get(i) + your_addition;

theList.set(i, a);
Orhan Obut
  • 8,756
  • 5
  • 32
  • 42
0

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);
        }
Kick
  • 4,823
  • 3
  • 22
  • 29