Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare an array in java without size

Tags:

java

arrays

Hello am trying to declare an array in java but i do not want the array to have a specific size because each time the size must be different.

I used this declaration: int[] myarray5;

but when am trying the below code there is an error on myarray5

for(int i=0; i<=myarray1.length - 1; i++){
    for (int j=0; j<=myarray2.length - 1; j++){
        if (myarray1[i] == myarray2[j]){
            myarray5[k] = myarray2[j];
            k++;
        }       
    }       
}

and also when am printing the array:

for (int i=0; i<=myarray3.length-1; i++){
    System.out.print(myarray3[i]+",");
}
like image 740
Christos Michael Avatar asked Jul 15 '15 19:07

Christos Michael


2 Answers

There is a NullPointerException because you declared but never initialized the array.

You can dynamically declare an array as shown below.

  int size = 5; // or anyother value you want
  int[] array = new int[size];

Or you use a list. Which allows to dynamically change the size. E.g:

  List<Integer> list = new ArrayList<>();
  list.add(5); //adds number 5 to the list
  int number = list.get(0); // Returns Element which is located at position 0 (so in this example in number will be "5");
like image 158
Denis Lukenich Avatar answered Sep 30 '22 15:09

Denis Lukenich


Couple of things, as people have said regular arrays in Java must be declared with a "new" statement as well as a size. You can have an empty array if you want, but it will be of size 0.

Now, if you want a dynamic array you can use an ArrayList. Its syntax is as follows:

ArrayList<Primitive_Type_Here> = new ArrayList<Primitive_Data_Type_Here>();

Now, once again if you do not tell the array what to have then there is no point in even doing anything with either array type. For ArrayLists you would have to tell it to add any object that fits its type. So for example I can add "Hello World" into an ArrayList we can do the following code.

ArrayList<String> sList = new ArrayList<String>();
sList.add("Hello World");
System.out.println("At index 0 our text is: " + sList.get(0));

//or if you want to use a loop to grab an item
for(int i = 0, size = sList.size(); i < size; i ++)
{
   System.out.println("At index " + i + " our text is: " + sList.get(i));
}

**If you are wondering why I am using .size() instead of .length is because arrayLists do not have a .length method, and .size does the same thing for it.

**if you are wondering why I have int = 0, size = sList.size(); it is because this way you enhance your code performance as your loop is of O(n) complexity, however if we were to do i < sList.size() it would be O(n) * sList.size() as you would constantly be calling sList.size() per iteration of your loop.

like image 42
SomeStudent Avatar answered Sep 30 '22 14:09

SomeStudent