Null Pointer Exception--need help tonight!
Hey there so I'm basically working on a bonus project for class and I'm having trouble with this null pointer exception. I'm supposed to create a class called SimpleSet that implements the dictionary interface but only uses keys, not values. The instructor gave us a jar file that contains all required classes to run SimpleSet. Anyway the method thats throwing the exception is the add method. Here's the code for the class:
Code Java:
import java.util.*;
public class SimpleSet<K extends Comparable<? super K>>
{
/* use SimpleSortedDictionary object to hold set items
Note: Value is not needed, just set it to Boolean */
private DictionaryInterface<K, Boolean> items;
/* default constructor */
public SimpleSet()
{
DictionaryInterface<K, Boolean> items = new SimpleSortedDictionary();
}
/* Adds a given object to the set. If the given object already exists in the set,
return false; otherwise, return true */
public boolean add(K item) //NOTE: this calls the dictionary interface method: public V add(K key, V value);
{
boolean result;
if(items.add(item, true) != null)
{
result = true;
}
else result = false;
return result;
}
/* Removes a given object from the set. */
public void remove(K item)
{
items.remove(item);
}
/* Sees whether the set contains a given object. */
public boolean contains(K item)
{
return items.contains(item);
}
/* Clears all objects from the set. */
public void clear()
{
items.clear();
}
/* Gets the number of objects in the set. */
public int getSize()
{
return items.getSize();
}
/* Returns an iterator to the set. */
public Iterator<K> getIterator()
{
return items.getKeyIterator();
}
/* Returns a set that combines the items in two sets
Note: the union of current ("this") set and input otherset. */
public SimpleSet<K> union(SimpleSet<K> otherSet)
{
return null;
}
/* Returns a set of those items that occur in both of two sets (the intersection).
Note: the intersection of current ("this") set and input otherset. */
public SimpleSet<K> intersection(SimpleSet<K> otherSet)
{
return null;
}
/* Display objects */
public String toString()
{
return "Set print out: "+this;
}
/* may define tests here */
public static void main(String args[])
{
SimpleSet setA = new SimpleSet();
Integer five = new Integer(5);
setA.add(five);
setA.toString();
}
} // end SimpleSet
error message:
Exception in thread "main" java.lang.NullPointerException
at SimpleSet.add(SimpleSet.java:22)
at SimpleSet.main(SimpleSet.java:83)
Re: Null Pointer Exception--need help tonight!
You declare a variable named items in your constructor that is NOT the same as the class variable named items. Then you attempt to use the uninitialized items variable in your add method, which causes the NPE.
When posting code, use the code tags. Take a look at any other post as an example.
How To Ask Questions The Smart Way