简体   繁体   English

Java ArrayList强制转换问题

[英]Java ArrayList Casting Issue

I have an ArrayList in Java which is full of int's. 我在Java中有一个充满int的ArrayList。 I am accessing it through get method. 我正在通过get方法访问它。 Now, I need array list int objects as ints to perform some operations. 现在,我需要将数组列表int对象作为int来执行一些操作。 So, what I am doing is, 所以,我正在做的是

int i = Integer.parseInt(arraylist.get(position).toString()) + 100 ...

Is there any-other nice way to do it (means efficiently) ? 还有其他更好的方法可以做到(有效地表示)吗?

Yes - don't convert to a string and back! 是的-不要转换为字符串然后返回!

int i = arrayList.get(position).intValue() + 100;

Or using auto-unboxing: 或使用自动拆箱:

int i = arrayList.get(position) + 100;

As noted in comments, I'm happy with auto-unboxing when the expression is just used in assignment expression (or as a method argument) - when it's used as part of an arithmetic expression, I generally prefer to make it explicit. 如评论中所述,当表达式仅用于赋值表达式(或用作方法参数)时,我对自动拆箱感到满意-当将其用作算术表达式的一部分时,我通常更喜欢使其明确。

(Note that your list will be full of Integer references, not int values.) (请注意,您的名单将以饱满的Integer参考,并不int值。)

What version of Java are you using? 您正在使用什么版本的Java? Since Java 1.5 the 'autoboxing' feature should take care of this for you. 从Java 1.5开始,“自动装箱”功能将为您解决这一问题。

int i = arrayList.get(position) + 100;

Perhaps: 也许:

List<Integer> myList = new ArrayList<Integer>();
myList.put(1);
myList.put(2);
...
int num = myList.get(index) + 100;

Or do whatever you like, collection will contain only Integers so you don't have to convert it. 或执行任何您喜欢的操作,集合将仅包含Integer,因此您无需进行转换。 Plus, autoboxing takes care for int->Integer and back. 另外,自动装箱会注意int-> Integer并返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM