Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating array without declaring the size - java

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

like image 379
Hamoudaq Avatar asked Aug 16 '12 15:08

Hamoudaq


People also ask

Can We declare an array without size in Java?

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.

How to declare an array variable in Java?

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.

How to create an array in Java?

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.

How to change the size of an array in Java?

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.


2 Answers

How about this

    private Object element[] = new Object[] {};
like image 193
user2720864 Avatar answered Sep 19 '22 12:09

user2720864


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);
like image 30
Martin Erhardt Avatar answered Sep 18 '22 12:09

Martin Erhardt