aspose file tools*
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


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dynamic Arrays" Watch "Dynamic Arrays" New topic
Author

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.:


Thanks


Moosey knows best
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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?

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

Joined: Oct 27, 2005
Posts: 19783
    
  20

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
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: http://aspose.com/file-tools
 
subject: Dynamic Arrays