开发者

Can I assign Java values from an ArrayList to different variables without hardcoding the size?

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 Array开发者_Python百科List 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:

    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 a try/catch.

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

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.


The easiest way to do this is:

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

If you insist on having the variables var1 through var5 rather than just using the array elements, copy the array elements to the variables. Alternatively you can replace all instances in your code of "= varN" with "=myArrayList.get(n)".


I agree with Voo that this is most likely from bad code design. But it's an opportunity for me to demonstrate my love of final variables and ternary expressions. :-) How's this? (For yuks I'm presuming 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;


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

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


The described design look realy ugly. You can use ternary operator for desired purpose though:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜