File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Dynamic Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic Arrays" Watch "Dynamic Arrays" New topic

Dynamic Arrays

Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191
i have an array:

I want to add values into it but when i try it tells me there is a NullPointerException. I understand what this means so my question is simply, therefore, how do you actually add values into the array. My code is similar to the following that is in a loop.:


Moosey knows best
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

You don't have an array. You have a variable of array type. You haven't allocated an array object for it to point to, so it's null. Therefore trying to store an object into it gives a NullPointerException.

int[] dynamicArray = new int[100];

[Jess in Action][AskingGoodQuestions]
Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191
Ah ok. Thanks. So is your method of creating an array with a pre-set length the best way to set up an array for an unknown number of values?

[ November 13, 2005: Message edited by: Sam Bluesman ]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

I think you can better use a List (ArrayList). This is a default interface from the java.util package which handles resizing for you.

There is one problem with List in Java 1.4 and earlier: you can't put primitives in. To put ints in a List you must create an Integer object and put that in the List. Likewise, when you retrieve it from the List, you must first cast the Object to Integer, than retrieve the value through intValue().

Java 1.5 can do much of this work for you. Firstly, you can create a List that can only except Integer objects. Secondly, autoboxing does the conversion between Integer and int for you.

Java 1.4:
Java 1.5:

How To Ask Questions How To Answer Questions
Sam Bluesman
Ranch Hand

Joined: Nov 21, 2004
Posts: 191
ok. Thanks guys.
I agree. Here's the link:
subject: Dynamic Arrays
It's not a secret anymore!