Reputation: 25412
So I know that Java treats arrays' sizes as immutable, but in other languages like PHP, I have been able to use []
to assign a value to the next index of an array:
$arr = array();
//Arr looks like this
$arr => {}
$arr[] = "Value";
//Arr looks like this
$arr => {"Value"}
Is there a similar function in Java?
int[] arr = new int[0];
arr[] = 3;
arr[] = 4;
//arr => [3, 4];
Upvotes: 0
Views: 3631
Reputation: 1320
In Java you have to set the number of elements in the array when you construct it. So you can't append more elements to the end of an array.
You can do the following to move to the next element in the array:
int[] arr = new int[2];
int = 0;
arr[i++] = 3;
arr[i++] = 4;
That works because i
is incremented after each array element is assigned.
If you really want to append to the end of a list, you should use a Java collection class. Unfortunately you can't have a collection of primitive types (like int
).
Upvotes: 0
Reputation: 2534
In java you have to set the size of the Array when you create it
int[] arr = new int[2];
Then once the array is created, you can add values to a specific index like this:
arr[0] = 3;
arr[1] = 4;
//Now arr = {3, 4}
However, you cannot add a third value to the array arr
because the size is fixed at 2. If you need to change the size of the array, an ArrayList
would be better. You can just use the add()
method and it will add values to the end of the array
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(3);
arr.add(4);
arr.add(5);
//Now arr contains the values {3, 4, 5}
//You can continue you add values
EDIT: Another option is to use the Arrays.copyOf(int[] arr, int size)
int[] arr = {3, 4};
//arr contains the values {3, 4}
int[] arr2 = Arrays.copyOf(arr, 4);
//arr2 contains the values {3, 4, 0, 0}
Upvotes: 6
Reputation: 960
As has been said, Java arrays cannot be resized. However, if you used ArrayList<Integer>
, you could use the add()
function to get the desired result.
Upvotes: 2
Reputation: 425298
Almost. There is a shorthand syntax for array creation:
int[] arr = {3, 4};
Otherwise use a List which resizes automatically:
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(4);
// etc
Upvotes: 0
Reputation: 8662
no. you have to use your own index or use an ArrayList
and the add
method
Upvotes: 0