-2

I want to teach myself java, and stumbled upon a problem. Coming from a python background, I would define an array (or list) like a = [] and then do something like a = [1,2,3,4,5]

In java, if I define an array like int[] a, I cannot assign values to it like a = {1,2,3,4,5};

Why? I certainly can initialize it like int[] a {1,2,3,4,5};, but why not assign it?

thx.

RamPrakash
  • 1,657
  • 3
  • 20
  • 24
Pythoneer
  • 165
  • 10
  • 2
    check this link [java arrays](http://stackoverflow.com/documentation/java/99/arrays#t=201702131329056142449) – matoni Feb 13 '17 at 13:29
  • 3
    You can only do that during initalization in java using the syntax for that: ``int[] a = new int[] {1,2,3,4,5};`` – f1sh Feb 13 '17 at 13:30
  • @f1sh But what if I want to change a into {5,2,4}? Do I always have to reinitialize a new array? – Pythoneer Feb 13 '17 at 13:36
  • @Pythoneer Arrays are very lightweight objects in Java. If you want more functionality, you have to either design your own class that wraps an array, or use one of the API's data structures, like `ArrayList`. – Jorn Vernee Feb 13 '17 at 13:38
  • use ``List`` http://stackoverflow.com/questions/5061721/how-can-i-dynamically-add-items-to-a-java-array – Donald Wu Feb 13 '17 at 13:48
  • List seems to be good, thx! – Pythoneer Feb 13 '17 at 13:49

1 Answers1

0

Array

int[] arr1 = new int[] { 1, 2, 3, 4, 5 };

int[] arr2 = new int[5];
arr2[0] = 1;
arr2[1] = 2;
arr2[2] = 3;
...

List

// Arrays#asList(T.. a)
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

// ArrayList
List<Integer> arrayList = new ArrayList<>();
list.add(1);
...

// LinkedList
List<Integer> linkedList = new LinkedList<>();
list.add(1);
...
Mincong Huang
  • 4,311
  • 5
  • 32
  • 53