ehsan akbari ehsan akbari - 3 months ago 6x
Java Question

How to set array elements after I have initialized it?

I am looking for a simple way to set the elements of an array after it is initialized. I have tried this :


public class Main {

public static void main(String[] args) {
int[] test = new int[6];
test = {1,2,3,4,5};

However compiling this gives error :

Error:(7, 16) java: illegal start of expression
Error:(7, 17) java: not a statement
Error:(7, 18) java: ';' expected
Error:(9, 1) java: class, interface, or enum expected

I can use this way to put values in the array:

test[0] = 1;
test[1] = 2;
test[2] = 3;
test[3] = 4;
// and so on.

I am just looking for a simple way to do that.


I know I can use this :

int[] test = {1,2,3,4};

But what I want is a simple way to put values in array after its initialization.

And one another thing : I am not looking for loops!


The answer @Python gave was what I was looking for!


You can simply do this by using Arrays's static method in one line:

Integer[] test = new Integer[10];

Note: using 'int' is also fine but then you to add explicit casting (int[])