0

I have an ArrayList in Java which is full of int's. I am accessing it through get method. Now, I need array list int objects as ints to perform some operations. 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) ?

3
  • 2
    "I have an ArrayList in Java which is full of int's". No, you don't. You can't store primitives in an ArrayList. You have an ArrayList of Integer objects. Commented May 1, 2012 at 10:09
  • @Jesper, Thanks. Sorry, I said it wrongly. I mean int objects. Commented May 1, 2012 at 13:48
  • No, you mean Integer objects. int is a primitive type; an int is not an object. Commented May 2, 2012 at 7:04

3 Answers 3

3

What version of Java are you using? Since Java 1.5 the 'autoboxing' feature should take care of this for you.

int i = arrayList.get(position) + 100;
Sign up to request clarification or add additional context in comments.

3 Comments

You haven't shown us where your array is instantiated. If you have it set up as an array of Integers this should work.
Ok sorry. I have not declared it as INT.
Ah, ok. I guess that was an assumption on my part.
3

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. Plus, autoboxing takes care for int->Integer and back.

Comments

3

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.)

3 Comments

Thanks a lot. Nice way to do.
With auto-unboxing, you can simplify it to int i = arrayList.get(position) + 100;
@GregKopff: While I suspected that would be okay, I wasn't 100% sure it would unbox as part of the arithmetic. I normally only use unboxing directly in assignment - I feel this ends up being clearer. Will add the option though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.