Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › [Java] Linked Lists, null pointer exceptions, and saving my sanity
New Posts  All Forums:Forum Nav:

[Java] Linked Lists, null pointer exceptions, and saving my sanity

post #1 of 4
Thread Starter 
I've been trying to fix a problem with my program for a few days now, and I cannot figure it out. I wrote a short test program in the class "LinkedList" to make sure that I'm creating the methods correctly. As you can see, I haven't gotten very far. I'm testing out the method "add(int newPosition, E newEntry)". In the test program, I'm trying to add the node to the list at position 0, but I'm getting a null pointer exception when I try to point head to the new node. I cannot figure out why I'm getting that null pointer exception. When the head is created, the "next" field is set to null. But when I call "head.setNextNode(n)", all that's doing is setting the "next" field of head to point to the new node. I'm completely lost as to why this is happening.
post #2 of 4
You never instantiate your head node in your linked list, therefore when you try to reference it, since it was never put into memory, it throws a NullPointerException(). Whenever you make an object make sure to always instantiate all of the objects you are using in the constructor. Heres the revised code:

Code:
import java.util.Comparator;
import java.util.Iterator;



public class LinkedList<E> implements ListInterface<E>, Iterable<E> {

/**
 * Stores true if the LinkedList has a comparator,
 * Stores false if the the LinkedList does not have a comparator. 
 */
private boolean hasComparator;

/**
 * Stores the size of the list;
 */
private int size = 0;

/**
 * Node designated as the head
 */
private Node<E> head;

/**
 * Initialize an empty list with client controlled order (i.e. no
 * Comparator)
 */
public LinkedList() {
hasComparator = false;
head = new Node<E>();
}

/**
 * Initialize an empty list with Comparator controlled order The add method
 * will maintain the order of elements based on the supplied Comparator
 * object.
 */
public LinkedList(Comparator<E> c) {
hasComparator = true;

}
/**
 * Gets the size of the list.  Used for debugging only
 */
public int getSize(){
return size;
}

/**
 * Adds a new entry to the list. If a Comparator was specified, the entry is
 * added to maintain non-decreasing order. Otherwise, the newEntry is added
 * at the end of the list. The list's size is increased by 1.
 * 
 * @param newEntry
 *            the object to be added as a new entry
 * @return The position where the item was inserted
 */
@Override
public int add(E newEntry) {
return -1;
}

/**
 * If no Comparator was specified, adds a new entry to the list at the
 * specified position. If a Comparator was specified, the method throws an
 * exception.
 * 
 * The list's size is increased by 1 if the add is successful.
 * 
 * @param newPosition
 *            The position in the list where the item is to be inserted
 * @param newEntry
 *            the object to be added as a new entry
 * @return true if the addition is successful
 * @throws UnsupportedOperationException
 *             if a Comparator was specified
 */
@Override
public boolean add(int newPosition, E newEntry) {
Node<E> n = new Node<E>(newEntry);
//if (newPosition<0 || newPosition>size)
//return false;
if (hasComparator == true)
throw new UnsupportedOperationException("Error: Comparator was specified");
if (newPosition == 0)
head.setNextNode(n);
size++;
return true;
}

/**
 * Gets the node at the specified LOCATION.  Note this is not the INDEX.  This method asks for the Location.
 * @param loc location of the node to be returned.  Must be greater or equal to 1, and less than or equal to size.
 * @return The node at the given location.
 * @throws IllegalArgumentException if the location is out of bound.
 */
public Node<E> getNodeAt(int loc){
if (loc<1 || loc>size)
throw new IllegalArgumentException("Location is out of bound");
Node<E> start = head;
for (int i=1; i<= loc; i++)
start = start.nextNode();
return start;
}

@Override
public void clear() {
//While the count is less than the size of the LinkedList,
//break the connection between 
int count = 0;
//while (count<size)


}

/**
 * Gets the entry at the given location.  givenPosition must be between 1 and size, inclusive.
 * @return the object located at givenPosition
 * 
 */
@Override
public E getEntry(int givenPosition) {
// TODO Return a reference to the indicated element
Node<E> loc = getNodeAt(givenPosition);
return loc.getData();
}

@Override
public int getLength() {
// TODO report the length (size) of the list
return 0;
}

@Override
public boolean isEmpty() {
// TODO Is the list empty
return false;
}

/**
 * Locates the first occurrence of the specified value If this list has a
 * Comparator, matches are determined by a compare value of zero, otherwise
 * the equals method is used.
 * 
 * @param anEntry
 *            The entry to be located
 * @return -1 if not found, otherwise the index of the first occurrence of
 *         anElement
 */
@Override
public int indexOf(E anEntry) {
// TODO Locate the item
return 0;
}

@Override
public E remove(int givenPosition) {
// TODO Remove the indicated item
return null;
}

/**
 * This operation is unsupported for lists with a Comparator
 */
@Override
public boolean replace(int givenPosition, E newEntry) {
// TODO Replace the item at the specified position
return false;
}

@Override
public Iterator<E> iterator() {
// TODO Create and return an Iterator
return null;
}

@Override
public void add(E[] e) {
// TODO adds all elements of e to the list
}

@Override
public E[] toArray(E[] a) {
// TODO returns an array containing the elements of the list.
return null;
}
/**
 * Test program to check operations of the linked list operate correctly
 * @param args
 */
public static void main (String[] args){
LinkedList<String> list = new LinkedList<String>();
System.out.println(list.add(0, "test 1"));
System.out.println(list.getSize());
//System.out.println(list.getEntry(1));
}


}
class LLIterator implements Iterator{

@Override
public boolean hasNext() {
// TODO Auto-generated method stub

return false;
}

@Override
public Object next() {
// TODO Auto-generated method stub
return null;
}

@Override
public void remove() {
// TODO Auto-generated method stub

}

}

Node:
Code:

public class Node<E> {

/**
 * variable to store the data.  Will accept any object.
 */
private E data;
/**
 * Link to the next node
 */
private Node<E> next;

/**
 * Constructor to create a new Node object
 * @param data object to be stored  
 */

public Node() {
this.data = null;
this.next = null;
}

public Node(E data){
this.data = data;
next = new Node<E>();
}

public Node(E data, Node<E> node) {
this.data = data;
this.next = node;
}
/**
 * Gets the data stored in the Node
 * @return data
 */
public E getData(){
return data;
}
/**
 * Gets the next node in the list
 * @return next node
 */
public Node<E> nextNode(){
return next;
}
/**
 * Sets the next node
 */
public void setNextNode(Node<E> n){
this.next = n;
}
}
All the code I changed or added is in bold. I added a default constructor to your Node class so you can use it on your next Node, this will just set the data to null and set the next Node to null.
baby cakes
(13 items)
 
Macbook 4,1
(13 items)
 
 
CPUMotherboardGraphicsRAM
i7 930 [4.01Ghz vCore 1.28125 HT on] GA-X58A-UD3R ZOTAC GTX 460 1GB SLI [840/1680/1900 @stock volts] CORSAIR XMS3 6GB (3 x 2GB) 1600Mhz 
Hard DriveOptical DriveOSMonitor
C300 64GB SATA III, 2x F3 1TB 7200rpm RAID 0 Sony Optiarc 24X DVD/CD Ubuntu 14.04 22" Dell SP2009W 1680x1050 
PowerCase
CORSAIR HX 750W Cooler Master HAF 922 
CPUMotherboardGraphicsRAM
Core 2 Duo 2.4Ghz Penryn T8300 Some logical board GMA X3100 4GB (2x2GB) DDR2 667Mhz 
Hard DriveOptical DriveOSMonitor
Hitachi 160 GB 5400 RPM SATA II Combo drive OSX 10.6.4 (Snow leopard) 13.3" 1280x800 TFT 
PowerCase
Dying battery White macbook case 
  hide details  
Reply
baby cakes
(13 items)
 
Macbook 4,1
(13 items)
 
 
CPUMotherboardGraphicsRAM
i7 930 [4.01Ghz vCore 1.28125 HT on] GA-X58A-UD3R ZOTAC GTX 460 1GB SLI [840/1680/1900 @stock volts] CORSAIR XMS3 6GB (3 x 2GB) 1600Mhz 
Hard DriveOptical DriveOSMonitor
C300 64GB SATA III, 2x F3 1TB 7200rpm RAID 0 Sony Optiarc 24X DVD/CD Ubuntu 14.04 22" Dell SP2009W 1680x1050 
PowerCase
CORSAIR HX 750W Cooler Master HAF 922 
CPUMotherboardGraphicsRAM
Core 2 Duo 2.4Ghz Penryn T8300 Some logical board GMA X3100 4GB (2x2GB) DDR2 667Mhz 
Hard DriveOptical DriveOSMonitor
Hitachi 160 GB 5400 RPM SATA II Combo drive OSX 10.6.4 (Snow leopard) 13.3" 1280x800 TFT 
PowerCase
Dying battery White macbook case 
  hide details  
Reply
post #3 of 4
Thread Starter 
I new it was something stupid I was missing. Thank you very much.
post #4 of 4
Quote:
Originally Posted by Hickeydog View Post
I new it was something stupid I was missing. Thank you very much.
It always is, glad I could help.
baby cakes
(13 items)
 
Macbook 4,1
(13 items)
 
 
CPUMotherboardGraphicsRAM
i7 930 [4.01Ghz vCore 1.28125 HT on] GA-X58A-UD3R ZOTAC GTX 460 1GB SLI [840/1680/1900 @stock volts] CORSAIR XMS3 6GB (3 x 2GB) 1600Mhz 
Hard DriveOptical DriveOSMonitor
C300 64GB SATA III, 2x F3 1TB 7200rpm RAID 0 Sony Optiarc 24X DVD/CD Ubuntu 14.04 22" Dell SP2009W 1680x1050 
PowerCase
CORSAIR HX 750W Cooler Master HAF 922 
CPUMotherboardGraphicsRAM
Core 2 Duo 2.4Ghz Penryn T8300 Some logical board GMA X3100 4GB (2x2GB) DDR2 667Mhz 
Hard DriveOptical DriveOSMonitor
Hitachi 160 GB 5400 RPM SATA II Combo drive OSX 10.6.4 (Snow leopard) 13.3" 1280x800 TFT 
PowerCase
Dying battery White macbook case 
  hide details  
Reply
baby cakes
(13 items)
 
Macbook 4,1
(13 items)
 
 
CPUMotherboardGraphicsRAM
i7 930 [4.01Ghz vCore 1.28125 HT on] GA-X58A-UD3R ZOTAC GTX 460 1GB SLI [840/1680/1900 @stock volts] CORSAIR XMS3 6GB (3 x 2GB) 1600Mhz 
Hard DriveOptical DriveOSMonitor
C300 64GB SATA III, 2x F3 1TB 7200rpm RAID 0 Sony Optiarc 24X DVD/CD Ubuntu 14.04 22" Dell SP2009W 1680x1050 
PowerCase
CORSAIR HX 750W Cooler Master HAF 922 
CPUMotherboardGraphicsRAM
Core 2 Duo 2.4Ghz Penryn T8300 Some logical board GMA X3100 4GB (2x2GB) DDR2 667Mhz 
Hard DriveOptical DriveOSMonitor
Hitachi 160 GB 5400 RPM SATA II Combo drive OSX 10.6.4 (Snow leopard) 13.3" 1280x800 TFT 
PowerCase
Dying battery White macbook case 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › [Java] Linked Lists, null pointer exceptions, and saving my sanity