1

A tiny annoyance I have in my code right now - these two lines of code:

int i = 1;
listOfIntegers.add(i);

I would really like these to be one line but I can't for the life of me find anything like "new int[] {1}" or similar. Is this possible?

1 Answer 1

1

Yes, it is, and it is as easy as possible :)

listOfIntegers.add(1);

PS : For primitive data types you dont have to create "instances" of them, they are instances itself.

Sign up to request clarification or add additional context in comments.

3 Comments

oh. OH. Bloody of course. The actual number is not so much 1 as it is a integer returned by a method but I can just as easily just... yes. I feel a bit silly now, thanks for the help.
@Klaabu - that happens :D, btw : you can even store a results of expressions by same approach. For example listOfIntegers.add(9-8); do the same as listOfIntegers.add(1);
Note that this code is using the auto-boxing feature of Java (auto-converting int into Integer). This is fine, but it's important to know what is going on behind the scenes. This article has some common gotchas: certpal.com/blogs/2009/08/autoboxing-unboxing-gotchas

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.