File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic Arrays

 
Sam Bluesman
Ranch Hand
Posts: 191
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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];
 
Sam Bluesman
Ranch Hand
Posts: 191
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20398
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Sam Bluesman
Ranch Hand
Posts: 191
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok. Thanks guys.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic