Is it possible to assign Java values ​​from ArrayList to various variables without hard-coding size?

I have an ArrayList, and we say that it can be no more than 5. I want to assign the first element to var1, the second to var2, the third to var3, etc.

However, sometimes an ArrayList will have less than 5 elements, in which case I will not assign a value to some variables.

So my question is: is there a better way to do this otherwise 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); 
+4
source share
5 answers

The source of this is, of course, poor code design. Also, why do you initialize a variable if the arraylist does not contain a field (you use it later)? A larger example or what exactly you are trying to do will help here. Usually just using

But I can at least two ways to do this:

  switch(myArrayList.size()) { case 5: var4 = myArrayList.get(4); case 4: var3 = myArrayList.get(3); case 3: var2 = myArrayList.get(2); // and so on } 

or just use try / catch.

  try { var0 = myArrayList.get(0); var1 = myArrayList.get(1); } catch(IndexOutOfBoundsException ex){ } 

But, of course, it is better to use the arraylist itself and just use it with the default values ​​that you would use for your variables.

+12
source

The easiest way to do this:

 Object[] vars = myArrayList.toArray(new Object[5]); 

If you insist that the var1 variables through var5 instead of just using the elements of the array, copy the elements of the array into the variables. Alternatively, you can replace all code instances of "= varN" with "= myArrayList.get (n)".

+3
source

I agree with Voo that this is most likely due to poor code design. But it gives me the opportunity to demonstrate my love for finite variables and triple expressions. :-) How is it? (For yuks, I assume an ArrayList of strings.)

 final Iterator<String> iter = myArrayList.iterator(); final String var1 = iter.hasNext() ? iter.next() : null; final String var2 = iter.hasNext() ? iter.next() : null; final String var3 = iter.hasNext() ? iter.next() : null; final String var4 = iter.hasNext() ? iter.next() : null; final String var5 = iter.hasNext() ? iter.next() : null; 
+1
source

How about using a separate array and assigning a value for each array to the corresponding value in the list in a loop?

 for (i = 0; i<= 5; i++) { var [i] = myArrayList.indexOf(i); } 
+1
source

The described design looks really ugly. You can use the ternary operator for the desired purpose:

 var1 = myArrayList.size() > 0 ? myArrayList.get(0) : "null"; 
0
source

All Articles