70
int[] array1 = {1, 2, 3, 4, 5, 6, ,7, 8}; - working


array1 = {1, 1, 1, 1, 2, 5, ,7, 8}; - NOT working

The first line is working, but second line is not working.

How can I make the initialization from the second line in one single line of code?

0

2 Answers 2

131
array = new int[] {1, 1, 2, 3, 5, 8};

Source: Oracle JavaDocs - Arrays

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

3 Comments

Add to your answer link to the documentation: java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
It is the "new" that is important.
@uthark: I don't see where this syntax is on the page that you linked. The closest it comes is the array copying at the bottom, but that's not exactly a one line solution. Can you be more specific?
6

The reason the first one works is because the compiler can check how many elements you are going to assign to the array, and then allocate the appropriate amount of memory.

EDIT: I realize now that you are just trying to update array1 with new data... Mike D's answer solves that.

1 Comment

FWIW if you send the array to something else (like a graphical list handler) and re-initialize the array like above, the link to the graphical list handler will break. I ran into this while developing with Android. So if you want to update the list, the best thing to do is clear it and add more items with its own tools. And never use new. :p

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.