i've digging around about the same issue but i couldn't find the same as i had
i want to create an array without declaring the size because i don't know how it will be !
to clear the issue i'd like to give you the code that i'm looking up for
public class t
{
private int x[];
private int counter=0;
public void add(int num)
{
this.x[this.counter] = num;
this.counter++;
}
}
as you see the user could use the add
function to add element to the array 10000 times or only once so it's unknown size
Q #1) Can we declare an Array without size? Answer: No. It is not possible to declare an array without specifying the size. If at all you want to do that, then you can use ArrayList which is dynamic in nature. Q #2) Is Array size fixed in Java? Answer: Yes. Arrays are static in Java and you declare an array with a specified size.
A Java array variable can also be declared like other variables with [] after the data type. The variables in the array are ordered and each have an index beginning from 0. Java array can be also be used as a static field, a local variable or a method parameter. The size of an array must be specified by an int or short value and not long.
Thus creating an array in Java involves two steps as shown below: int[] myarray; //declaration myarray = new int[10]; //instantiation. Once the array is created, you can initialize it with values as follows: myarray[0] = 1; myarray[1] = 3; ….and so on until all elements are initialized.
Arrays in Java have fixed size. Once declared, you cannot change it. If you try to force you way. You are creating a new array each time. Please do not create array1 to arrayN for any reasons. If you want dynamic size, which can stretch and shrink. You are looking for ArrayList. ArrayList in Java is easy to use.
How about this
private Object element[] = new Object[] {};
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With