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?

Peter
  • 703
  • 1
  • 5
  • 4

2 Answers2

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

Source: Oracle JavaDocs - Arrays

winklerrr
  • 13,026
  • 8
  • 71
  • 88
MikeD
  • 3,348
  • 1
  • 23
  • 36
  • 2
    Add to your answer link to the documentation: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html – uthark Jul 01 '10 at 17:55
  • 2
    It is the "new" that is important. – Thorbjørn Ravn Andersen Jul 01 '10 at 17:59
  • 1
    @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? – MikeD Jul 01 '10 at 18:07
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.

Dolph
  • 49,714
  • 13
  • 63
  • 88
  • 1
    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 –  Sep 12 '12 at 18:09