Ok, I've been fooling with this a while - this program is supposed to sort an array of strings, and it works fine...as long as I've defined the size of the array beforehand, and I want it to be of a variable size, as in one time you run the program, you may enter 3 items, another time, 5. Here's my code:
import java.util.*; import java.io.*; import java.lang.String; //alphabetical sort of names public class SortNames { //with the array filled like this (and the rest of the program modified) //this program works fine. //private static String [] name = {"John","Joe","Richard","Paul"}; private static BufferedReader stdin; SortNames() { } public static void main(String[] args) throws IOException { //50 seems to be a nice number String [] name1 = new String[50]; //"initialize" entered String entered = "nothing"; stdin = new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter the names to be sorted: "); int index = 0; while (entered.length() != 0) //i.e. nothing on line { entered = stdin.readLine(); //read a string if (entered.length() == 0) break; //if nothing is entered, get out name1[index] = entered; //put the string into the name1 array index++; } System.out.println("index= "+index); //for debugging String [] name = new String[index]; //idea behind this: create a variable length array Arrays.sort(name); //sort in java.util.Array for(int j=0;j<name.length;j++) System.out.println("name= "+name[j]); } }
I get a NullPointerException after entering the strings (once the program comes to the "Arrays.sort" line). I can't seem to figure out what the problem is. What did I do wrong?
1 the String array object was initialized, true, but probrably most of the elements are null. you should use Arrays.fill() to initialize wach element to an initial value, or be sure too check for nulls, which might screw up the Arrays.sort() , so initialize to "" or a non alpha character at the end of the alphabet in ascii.
2 to overcome the array problem, usethe dynamic array of java.util.Vector class.
Vectors can be flexible allowing growth, Vectors convert to arrays easily even allowing various types of arrays to be used. Vectors are pre initialized
Vector V = new Vector(24,8); // starts out size=24, grows 8 each time the load is increased
while(true)
{
String entry=stdin.readline();
if(entry==null||entry.length<1)break;
V.add(entry);
}
String[] names=new String[V.size]; // build the correct sized String[] ... exactly
V.toArray(names); /// fill names, casting the Objects stored in V to Strings
names.sort();
k=0;
while (k< names.length) System.out.println(new StringBuffer(k).append("\t").append(names[k++]);
1 the String array object was initialized, true, but probrably most of the elements are null. you should use Arrays.fill() to initialize wach element to an initial value, or be sure too check for nulls, which might screw up the Arrays.sort() , so initialize to "" or a non alpha character at the end of the alphabet in ascii.
2 to overcome the array problem, usethe dynamic array of java.util.Vector class.
Vectors can be flexible allowing growth, Vectors convert to arrays easily even allowing various types of arrays to be used. Vectors are pre initialized
Vector V = new Vector(24,8); // starts out size=24, grows 8 each time the load is increased
Reader stdin = new BufferedReader (new InputStreamReader(System.in));
while(true)
{
try
{
String entry=stdin.readline();
if (entry==null||entry.length<1)break;
V.add(entry);
}catch(Exception XX){XX.printStackTrace();}
}
String[] names=new String[V.size]; // build the correct sized String[] ... exactly
V.toArray(names); /// fill names, casting the Objects stored in V to Strings
names.sort();
k=0;
while (k< names.length) System.out.println(new StringBuffer(k).append("\t").append(names[k++]);
Just an FYI...Vector is thread-safe and carries the related overhead. ArrayList also implements the List interface, but is not synchronized. Thus, you should use ArrayList instead of Vector wherever possible and only refer to the specific type (Vector or ArrayList) at creation time...never in the rest of your code. All other references should simply refer to a List collection.
I had this same belief and wrote some tests to see how Vector and ArrayList stacked up. They were very close, but to my surprise, Vector came out faster. Of course, these were pretty simple tests and completely lacking in scientific vigor, I'm sure. I wonder if there are some more rigorous benchmarks posted somewhere that would justify the ArrayList-instead-of-Vector-except-when-you-need-synchronization argument? Maybe there are other considerations like memory efficiency to consider, as well?
As far as using List references and only using the the specific object type at creation, I agree completely. You really only need to use an ArrayList reference when you need a method that ArrayList has, but List does not.