I have an ArrayList, and we’ll say it can be at most size 5. I want to assign the first element to var1, the second to var2, the third to var3, etc.
However, sometimes the ArrayList will have less than 5 items, in which case I won’t be assigning some variables a value.
So my question is, is there a better way to do this other than:
if (myArrayList.size() > 0)
var1 = myArrayList.get(0);
if (myArrayList.size() > 1)
var2 = myArrayList.get(1);
if (myArrayList.size() > 2)
var3 = myArrayList.get(2);
if (myArrayList.size() > 3)
var4 = myArrayList.get(3);
if (myArrayList.size() > 4)
var5 = myArrayList.get(4);
The source of this is most certainly a bad code design. Also to what do you initialize the variable if the arraylist doesn’t contain the field (after all you use it later)? A larger example or what exactly you’re trying to do would help here. Usually just using
But I can think of at least two ways to do this:
or just use a try/catch.
But most certainly it’s better to use the arraylist itself and just padd it with the default values you’d otherwise use for your variables.