我可以将 ArrayList 中的 Java 值分配给不同的变量而不对大小进行硬编码吗?
我有一个 ArrayList,我们会说它的大小最多为 5。我想将第一个元素分配给 var1,第二个元素分配给 var2,第三个元素分配给 var3,等等。
但是,有时 ArrayList 的大小小于 5项目,在这种情况下,我不会为某些变量分配值。
所以我的问题是,除了以下方法之外,还有更好的方法吗?
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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
其根源肯定是糟糕的代码设计。另外,如果 arraylist 不包含该字段(毕竟您稍后使用它),您如何初始化变量?一个更大的例子或者你到底想做什么会有所帮助。通常只是使用
但我可以想到至少两种方法来做到这一点:
或者只是使用 try/catch。
但最肯定的是,最好使用数组列表本身,并用您本来用于变量的默认值填充它。
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.
最简单的方法是:
如果您坚持使用变量 var1 到 var5 而不仅仅是使用数组元素,请将数组元素复制到变量中。或者,您可以将代码中“= varN”的所有实例替换为“=myArrayList.get(n)”。
The easiest way to do this is:
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)".
我同意 Voo 的观点,这很可能是由于糟糕的代码设计造成的。但这对我来说是一个展示我对最终变量和三元表达式的热爱的机会。 :-) 这个怎么样? (对于 yuks,我假设是一个字符串的 ArrayList。)
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.)
如何使用单独的数组并在循环中为每个数组分配列表中相应值的值?
How about using a separate array and assigning the value for each array for corresponding value on the list in a loop?
所描述的设计看起来真的很难看。您可以使用三元运算符来达到所需的目的:
The described design look realy ugly. You can use ternary operator for desired purpose though: