Facing an error while assigning values to a list

helen :

I have a list which has 3 elements. It is in a while loop and I want to overwrite its values in each iterations. Here is the code:

private List<Integer> loadList = new ArrayList<>(3);
.
.
.
while(counter < 10) {
    loadList.add(0, taskNum);
    loadList.add(1, taskNum);
    loadList.add(2, taskNum);
    .
    .
    .
    counter++;
}

But after running the code I realized that overwriting is not happening and each time the new elements are being added to the end of the list. For example:

At first : a = [1 2 3]

Then: a = [1 2 3 4 5 6] but I want it to be like a = [4 5 6]

So I changed my code to something like this:

loadList = new ArrayList<>(3);
//initializing
loadList.add(0, 0);
loadList.add(1, 0);
loadList.add(2, 0);
while(counter < 10) {
    loadList.set(0, taskNum);
    loadList.set(1, taskNum);
    loadList.set(2, taskNum);
    .
    .
    .
    counter++;
}

But now I'm getting this error:

2018-11-24 13:27:38.298 ERROR [n.f.core.Main] Exception in main
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:657) ~[na:1.8.0_151]
    at java.util.ArrayList.set(ArrayList.java:448) ~[na:1.8.0_151]
    at net.floodlightcontroller.mactracker.Mactracker.paramInit(Mactracker.java:137) ~[floodlight.jar:1.2-SNAPSHOT]
    at net.floodlightcontroller.mactracker.Mactracker.init(Mactracker.java:205) ~[floodlight.jar:1.2-SNAPSHOT]
    at net.floodlightcontroller.core.module.FloodlightModuleLoader.initModules(FloodlightModuleLoader.java:460) ~[floodlight.jar:1.2-SNAPSHOT]
    at net.floodlightcontroller.core.module.FloodlightModuleLoader.loadModulesFromList(FloodlightModuleLoader.java:295) ~[floodlight.jar:1.2-SNAPSHOT]
    at net.floodlightcontroller.core.module.FloodlightModuleLoader.loadModulesFromConfig(FloodlightModuleLoader.java:235) ~[floodlight.jar:1.2-SNAPSHOT]
    at net.floodlightcontroller.core.Main.main(Main.java:61) ~[floodlight.jar:1.2-SNAPSHOT]

What's wrong and how can I solve this problem?

forpas :

With this line:

loadList = new ArrayList<>(3);

you defined that the initial capacity of the list is 3.
Now you can add as many items as you want not only 3.
But still your list is empty.
You cannot use:

loadList.set(2, taskNum);

if there is no item in the 3d position.
set(position, item) is valid only if there is already an item at position.
So use add(item) to add new items at the end of the list
and set(position, item) to replace the item that is already in the list at position.
You can also use add(position, item) to insert a new item at position, and shift the items from this position to the right.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111452&siteId=1