1

How may I define an array in Java. when I am not sure of the Arrays size. I am doing it to avoid Null Pointers

int[] arr1 = new int[21];
int[] arr1 = {11,22,33};

These are of fixed length, i need to declare an Array where the items to be stored in it will be decided at run time?

user3833732
  • 886
  • 9
  • 14

3 Answers3

2

You could use an ArrayList, which dynamically grows/shrinks according to how many elements you place/remove in it.

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
1

if you are not sure just declare it like this:

int[] arr1;

but you must know its size when you initialise it later:

arr1 = int[20];
//or
arr1 = {1, 2, 3};

On the other hand this is the situation where you should use List (like ArrayList) since they resize dynamically.

EDIT:

 List<Integer> list = new ArrayList<Integer>(); 
 //adding 
 list.add(2);

more methods here: http://docs.oracle.com/javase/7/docs/api/java/util/List.html

Lucas
  • 3,181
  • 4
  • 26
  • 45
0

"Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk."

ArrayList Tutorial

Harry
  • 3,031
  • 7
  • 42
  • 67