I have a project in which I had to allow a user to enter employees into a hash table, however we couldn’t use the predefined hash table stuff. I ended up going with an array of arraylists, and the constructor gave it a value, so that it wouldn’t get a nullpointerexception… and then it got one anyways, on the first line that used the hashtable. I commented out that snippet because it wasn’t absolutely necessary, and then the same issue cropped up in the next instance of hash.
The class and constructor:
public class Hash {
private ArrayList<Employee>[] hash = (ArrayList<Employee>[])new ArrayList[5];
//
public Hash()
{
ArrayList<Employee>[] q = (ArrayList<Employee>[])new ArrayList[5];
hash=q;
}
and the code where it breaks down:
do
{
p = (int) (Math.random( )*999999) + 1 ;
for (int w = 0; w<5; w++)
{
boolean t = hash[w].isEmpty(); // The line where I get the NPE Error
if (t=false)
{
for (int r = 0 ; r<hash[w].size(); r++) //where it shows up if I comment out the above.
{
o=o||p==(hash[r].get(w).geteN());
}
}
}
}
while (o = true);
I’m really not sure how to handle this one… Thanks in advance.
Remember that when you declare an
ArrayofObjectsin Java, you have to set each element of theArrayto something. Otherwise you just have an array ofnulls.Try this in your constructor instead:
The exception is if you declare an
Arrayof primitives (such asint,double, and so on), and then you get zeros instead.