I'm not sure if there is something wrong with my copy constructor for my queue (DSQueue) or if there is another reason for my problem. The copy constructor seems to copy the contents fine but if I try to manipulate the queue that was copied, the program fails. I've done some testing in my Queue's main method (see below) and I've run through a debugger. The IDE points out a NullPointerException when I try to change a queue in the line testQ.list.add(new Token(1)); in my main method. This line gets the token fine but it doesn't begin the add method. Not sure why...
public class DSQueue extends Queue {
public static void main(String[] args) {
DSQueue testQ = new DSQueue();
System.out.println("Size of testQueue: " + testQ.theQueue.size());
testQ.offer(new Token(100));
testQ.offer(new Token(200));
System.out.println("Size of testQueue after adding: " + testQ.theQueue.size());
System.out.println("\ntestQueue: " + testQ);
// TETING COPY CONSTRUCTOR
DSQueue newQ = new DSQueue(testQ);
System.out.println("New queue (should be the same as testQueue): " + newQ + " - size: " + newQ.size());
System.out.println("\nAfter changing one queue...");
testQ.list.add(new Token(1));
System.out.println("testQ: " + testQ + " - size: " + testQ.size());
System.out.println("New queue: " + newQ + " - size: " + newQ.size());
}
// The list containing the data
private DSList theQueue;
public DSQueue() {
theQueue = new DSList();
}
public DSQueue(Queue s) {
this();
// Cast s to a DSQueue type
DSQueue sCasted = (DSQueue)s;
// Create a reference for the Queue to be copied
Node queueToCopy = sCasted.theQueue.head;
while(queueToCopy != null) {
this.offer(queueToCopy.getToken());
queueToCopy = queueToCopy.next;
}
}
}
public abstract class Queue {
public DSList list;
public abstract boolean offer(Token t);
public abstract Token poll();
public abstract Token peek();
#Override
public abstract String toString();
public abstract int size();
public abstract boolean isEmpty();
}
public class DSList implements List {
public Node head;
public DSList() {
head = null;
}
public DSList(Node head_) {
head = head_;
}
// Copy constructor.
public DSList(DSList other) {
// Create a reference for the list to be copied
Node oldListNode = other.head;
while (oldListNode != null) {
this.add(oldListNode.getToken());
oldListNode = oldListNode.next;
}
}
/**
* Appends the specified element to the end of this list.
* #param obj The object to add.
* #return True if the object has been added to the list.
*
* #throws NullPointerException if the specified object is null.
*/
public boolean add(Token obj) {
if (obj == null) {
throw new NullPointerException();
}
// If list is empty, add new node to front.
if(isEmpty()) {
// Create a new Node. Add Token obj as data
Node newNode = new Node(null, null, obj);
// point head to new Node, newNode
head = newNode;
return true;
} else {
// create a reference of the start position in the list
Node current = head;
// While there are nodes remaining in the list, advance through to reach the end.
while (current.next != null)
current = current.next;
// Create a new node and append it to the end of the list, with 'prev' pointing to current (2nd to last node)
Node newNode = new Node(null, current, obj);
// Point old last element to the newest, last node in the list (in next variable)
current.next = newNode;
// Return true if successful addition of node.
return true;
}
}
}
public class Token {
public enum Type { OPERATOR, OPERAND, PAREN };
public Type type;
private String operator;
private double operand;
public Token(double result) {
this.operand = result;
this.type = Type.OPERAND;
}
}
public class Node {
public Node next;
public Node prev;
// data being stored in each node
private Token t;
// Node constructor
public Node(Node next, Node prev, Token token) {
this.next = next;
this.prev = prev;
this.t = token;
}
public Token getToken() {
return t;
}
}
Related
This question already has an answer here:
Java generics - The type parameter String is hiding the type String
(1 answer)
Closed last month.
Hello I have two java classes "List" and "ListPlayground". The problem is i can´t override the toString() Method, because I get this Error:
error: toString() in List cannot override toString() in Object
public String toString() {
^
return type String is not compatible with java.lang.String
where String is a type-variable:
String extends Object declared in class List
List.java:59: error: incompatible types: java.lang.String cannot be converted to String
String string = "";
^
where String is a type-variable:
String extends Object declared in class List
Note: List.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
Here is the class I have
public class List<String> {
private class Node {
private String element = null;
private Node next = null;
private Node(String element, Node next) {
this.element = element;
this.next = next;
}
private Node(String element) {
this.element = element;
}
}
private Node head = null;
private Node current = head;
public void prepend(String object) {
head = new Node(object, head);
}
public void append(String object) {
if(head == null) {
head = new Node(object);
return;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(object);
}
public String first() {
get(0);
}
public String get(int index) {
Node current = head;
for(int i = 0; i < index; i++) {
current = current.next;
}
return current.element;
}
public int size() {
Node current = head;
int size = 0;
for(; current != null; size++) {
current = current.next;
}
return size;
}
public String toString() {
String string = "";
while(current != null) {
string += head.element + " -> ";
current = head.next;
}
return string;
}
}
Here is the ListPlayground class:
public class ListPlayground {
public static void main(String[] args) {
List<String> stringliste = new List()<>;
stringliste.append("World");
stringliste.append("!");
stringliste.prepend("Hello");
System.out.println("The Length of the List is: " + stringliste.size());
System.out.println("The first Element of the List is: " + stringliste.first());
System.out.println("The element with Index 2 is: " + stringliste.get(2));
System.out.println("The last element is: " + stringliste.get(stringliste.size() - 1));
System.out.println("The whole List is: " + stringliste.toString());
System.out.println("And again the whole List " + stringliste.toString());
}
}
can somebody help me?
I tried to debug my code but I did not succeed. I know that the class "Object" is the superclass of all classes and I have to override the toString() Method, but I do not understand why the toString() method is wrong i the List class?
It's because your generic type is called String, which is shadowing the java.lang.String class. They both extend the Object, but they are fundamentally different.
To fix this problem, call your generic argument something else.
i.e.:
public class List<T> {
private class Node {
private T element = null;
private Node next = null;
private Node(T element, Node next) {
this.element = element;
this.next = next;
}
private Node(T element) {
this.element = element;
}
}
private Node head = null;
private Node current = head;
public void prepend(T object) {
head = new Node(object, head);
}
public void append(T object) {
if(head == null) {
head = new Node(object);
return;
}
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(object);
}
public T first() {
get(0);
}
public T get(int index) {
Node current = head;
for(int i = 0; i < index; i++) {
current = current.next;
}
return current.element;
}
public int size() {
Node current = head;
int size = 0;
for(; current != null; size++) {
current = current.next;
}
return size;
}
public String toString() {
String string = "";
while(current != null) {
string += head.element + " -> ";
current = head.next;
}
return string;
}
}
or you could just specify which String you want to return in the toString() method
i.e.:
public java.lang.String toString() {
java.lang.String string = "";
while(current != null) {
string += head.element + " -> ";
current = head.next;
}
return string;
}
Generally I would prefer solution 1) over 2). It's never a good idea to introduce a generic parameter which shadows a class name.
When you use public class List<String>, "String" is used as a generic type and not java.lang.String.
You should change your class declaration and remove the type as you don't need it.
public class List {
... your code here
}
public class List<T> is same as public class List<String> and in both the cases, it is generic type and not a java.lang.String type.
A List<String> class is declared in the code, which syntactically is like declaring a List<T> class where the "T" is called "String."
So when you try to do the override the compiler is like seeing this:
public T toString()
Also in the implemation of the toString method it is very inefficient to use the +=, it uses a StringBuilder instead.
im working on java tree and getting stuck on setting toString for LinkedBinaryTree and mapping yes/no to left/right child.
files im using:
AbstractBinaryTree.java
import java.util.ArrayList;
import java.util.List;
/** An abstract base class providing some functionality of the BinaryTree interface. */
public abstract class AbstractBinaryTree<E> extends AbstractTree<E> implements BinaryTree<E> {
/** Returns the Position of p's sibling (or null if no sibling exists). */
public Position<E> sibling(Position<E> p) {
Position<E> parent = parent(p);
if (parent == null) { // p must be the root
return null;
}
if (p == left(parent)) { // p is a left child
return right(parent); // (right child might be null)
} else { // p is a right child
return left(parent); // (left child might be null)
}
}
/** Returns the number of children of Position p. */
public int numChildren(Position<E> p) {
int count = 0;
if (left(p) != null) {
count++;
}
if (right(p) != null) {
count++;
}
return count;
}
/** Returns an iterable collection of the Positions representing p's children. */
public Iterable<Position<E>> children(Position<E> p) {
List<Position<E>> snapshot = new ArrayList<>(2); // max capacity of 2
if (left(p) != null) {
snapshot.add(left(p));
}
if (right(p) != null) {
snapshot.add(right(p));
}
return snapshot;
}
/** Adds positions of the subtree rooted at Position p to the given snapshot. */
private void inorderSubtree(Position<E> p, List<Position<E>> snapshot) {
if (left(p) != null) {
inorderSubtree(left(p), snapshot);
}
snapshot.add(p);
if (right(p) != null) {
inorderSubtree(right(p), snapshot);
}
}
/** Returns an iterable collection of positions of the tree, reported in inorder. */
public Iterable<Position<E>> inorder() {
List<Position<E>> snapshot = new ArrayList<>();
if (!isEmpty()) {
inorderSubtree(root(), snapshot); // fill the snapshot recursively
}
return snapshot;
}
/** Overrides positions to make inorder the default order for binary trees. */
public Iterable<Position<E>> positions() {
return inorder();
}
}
AbstractTree.java
import java.util.Iterator;
import java.util.List; // for use as snapshot iterator
import java.util.ArrayList; // for use as snapshot iterator
/** An abstract base class providing some functionality of the Tree interface. */
public abstract class AbstractTree<E> implements Tree<E> {
/** Returns true if Position p has one or more children. */
public boolean isInternal(Position<E> p) {
return numChildren(p) > 0;
}
/** Returns true if Position p does not have any children. */
public boolean isExternal(Position<E> p) {
return numChildren(p) == 0;
}
/** Returns true if Position p represents the root of the tree. */
public boolean isRoot(Position<E> p) {
return p == root();
}
/** Returns the number of children of Position p. */
public int numChildren(Position<E> p) {
int count = 0;
for (Position child : children(p))
count++;
return count;
}
/** Returns the number of nodes in the tree. */
public int size() {
int count = 0;
for (Position p : positions())
count++;
return count;
}
/** Tests whether the tree is empty. */
public boolean isEmpty() {
return size() == 0;
}
/** Returns the number of levels separating Position p from the root. */
public int depth(Position<E> p) throws IllegalArgumentException {
if (isRoot(p))
return 0;
else
return 1 + depth(parent(p));
}
/** Returns the height of the tree. */
private int heightBad() { // works, but quadratic worst-case time
int h = 0;
for (Position<E> p : positions())
if (isExternal(p)) // only consider leaf positions
h = Math.max(h, depth(p));
return h;
}
/** Returns the height of the subtree rooted at Position p. */
public int height(Position<E> p) throws IllegalArgumentException {
int h = 0; // base case if p is external
for (Position<E> c : children(p))
h = Math.max(h, 1 + height(c));
return h;
}
/** This class adapts the iteration produced by positions() to return elements. */
private class ElementIterator implements Iterator<E> {
Iterator<Position<E>> posIterator = positions().iterator();
public boolean hasNext() {
return posIterator.hasNext();
}
public E next() {
return posIterator.next().getElement();
} // return element!
public void remove() {
posIterator.remove();
}
}
/** Returns an iterator of the elements stored in the tree. */
public Iterator<E> iterator() {
return new ElementIterator();
}
/** Returns an iterable collection of the positions of the tree. */
public Iterable<Position<E>> positions() {
return preorder();
}
/** Adds positions of the subtree rooted at Position p to the given snapshot using a preorder traversal. */
private void preorderSubtree(Position<E> p, List<Position<E>> snapshot) {
snapshot.add(p); // for preorder, we add position p before exploring subtrees
for (Position<E> c : children(p))
preorderSubtree(c, snapshot);
}
/** Returns an iterable collection of positions of the tree, reported in preorder. */
public Iterable<Position<E>> preorder() {
List<Position<E>> snapshot = new ArrayList<>();
if (!isEmpty())
preorderSubtree(root(), snapshot); // fill the snapshot recursively
return snapshot;
}
/** Adds positions of the subtree rooted at Position p to the given snapshot using a postorder traversal. */
private void postorderSubtree(Position<E> p, List<Position<E>> snapshot) {
for (Position<E> c : children(p))
postorderSubtree(c, snapshot);
snapshot.add(p); // for postorder, we add position p after exploring subtrees
}
/** Returns an iterable collection of positions of the tree, reported in postorder. */
public Iterable<Position<E>> postorder() {
List<Position<E>> snapshot = new ArrayList<>();
if (!isEmpty())
postorderSubtree(root(), snapshot); // fill the snapshot recursively
return snapshot;
}
/** Returns an iterable collection of positions of the tree in breadth-first order. */
public Iterable<Position<E>> breadthfirst() {
List<Position<E>> snapshot = new ArrayList<>();
if (!isEmpty()) {
Queue<Position<E>> fringe = new LinkedQueue<>();
fringe.enqueue(root()); // start with the root
while (!fringe.isEmpty()) {
Position<E> p = fringe.dequeue(); // remove from front of the queue
snapshot.add(p); // report this position
for (Position<E> c : children(p))
fringe.enqueue(c); // add children to back of queue
}
}
return snapshot;
}
}
BinaryTree.java
/** An interface for a binary tree, in which each node has at most two children. */
public interface BinaryTree<E> extends Tree<E> {
/** Returns the Position of p's left child (or null if no child exists). */
Position<E> left(Position<E> p) throws IllegalArgumentException;
/** Returns the Position of p's right child (or null if no child exists). */
Position<E> right(Position<E> p) throws IllegalArgumentException;
/** Returns the Position of p's sibling (or null if no child exists). */
Position<E> sibling(Position<E> p) throws IllegalArgumentException;
}
LinkedBinaryTree.java
/** Concrete implementation of a binary tree using a node-based, linked structure. */
public class LinkedBinaryTree<E> extends AbstractBinaryTree<E> {
// ---------------- nested Node class ----------------
protected static class Node<E> implements Position<E> {
private E element; // an element stored at this node
private Node<E> parent; // a reference to the parent node (if any)
private Node<E> left; // a reference to the left child (if any)
private Node<E> right; // a reference to the right child (if any)
/** Constructs a node with the given element and neighbors. */
public Node(E e, Node<E> above, Node<E> leftChild, Node<E> rightChild) {
element = e;
parent = above;
left = leftChild;
right = rightChild;
}
// accessor methods
public E getElement() {
return element;
}
public Node<E> getParent() {
return parent;
}
public Node<E> getLeft() {
return left;
}
public Node<E> getRight() {
return right;
}
// update methods
public void setElement(E e) {
element = e;
}
public void setParent(Node<E> parentNode) {
parent = parentNode;
}
public void setLeft(Node<E> leftChild) {
left = leftChild;
}
public void setRight(Node<E> rightChild) {
right = rightChild;
}
} // ----------- end of nested Node class -----------
/** Factory function to create a new node storing element e. */
protected Node<E> createNode(E e, Node<E> parent, Node<E> left, Node<E> right) {
return new Node<E>(e, parent, left, right);
}
// LinkedBinaryTree instance variables
protected Node<E> root = null; // root of the tree
private int size = 0; // number of nodes in the tree
// constructor
public LinkedBinaryTree() { } // constructs an empty binary tree
// nonpublic utility
/** Validates the position and returns it as a node. */
protected Node<E> validate(Position<E> p) throws IllegalArgumentException {
if (!(p instanceof Node)) {
throw new IllegalArgumentException("Not valid position type");
}
Node<E> node = (Node<E>) p; // safe cast
if (node.getParent() == node) { // our convention for defunct node
throw new IllegalArgumentException("p is no longer in the tree");
}
return node;
}
// accessor methods (not already implemented in AbstractBinaryTree)
/** Returns the number of nodes in the tree. */
public int size() {
return size;
}
/** Returns the root Position of the tree (or null if tree is empty). */
public Position<E> root() {
return root;
}
/** Returns the Position of p's parent (or null if p is root). */
public Position<E> parent(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return node.getParent();
}
/** Returns the Position of p's left child (or null if no child exists). */
public Position<E> left(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return node.getLeft();
}
/** Returns the Position of p's right child (or null if no child exists). */
public Position<E> right(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
return node.getRight();
}
// update methods supported by this class
/** Places element e at the root of an empty tree and returns its new Position. */
public Position<E> addRoot(E e) throws IllegalStateException {
if (!isEmpty()) {
throw new IllegalStateException("Tree is not empty");
}
root = createNode(e, null, null, null);
size = 1;
return root;
}
/** Creates a new left child of Position p storing element e; returns its Position. */
public Position<E> addLeft(Position<E> p, E e) throws IllegalArgumentException {
Node<E> parent = validate(p);
if (parent.getLeft() != null) {
throw new IllegalArgumentException("p already has a left child");
}
Node<E> child = createNode(e, parent, null, null);
parent.setLeft(child);
size++;
return child;
}
/** Creates a new right child of Position p storing element e; returns its Position. */
public Position<E> addRight(Position<E> p, E e) throws IllegalArgumentException {
Node<E> parent = validate(p);
if (parent.getRight() != null) {
throw new IllegalArgumentException("p already has a right child");
}
Node<E> child = createNode(e, parent, null, null);
parent.setRight(child);
size++;
return child;
}
/** Replaces the element at Position p with e and returns the replaced element. */
public E set(Position<E> p, E e) throws IllegalArgumentException {
Node<E> node = validate(p);
E temp = node.getElement();
node.setElement(e);
return temp;
}
/** Attaches trees t1 and t2 as left and right subtrees of external p. */
public void attach(Position<E> p, LinkedBinaryTree<E> t1, LinkedBinaryTree<E> t2) throws IllegalArgumentException {
Node<E> node = validate(p);
if (isInternal(p)) {
throw new IllegalArgumentException("p must be a leaf");
}
size += t1.size() + t2.size();
if (!t1.isEmpty()) { // attach t1 as left subtree of node
t1.root.setParent(node);
node.setLeft(t1.root);
t1.root = null;
t1.size = 0;
}
if (!t2.isEmpty()) { // attach t2 as right subtree of node
t2.root.setParent(node);
node.setRight(t2.root);
t2.root = null;
t2.size = 0;
}
}
/** Removes the node at Position p and replaces it with its child, if any. */
public E remove(Position<E> p) throws IllegalArgumentException {
Node<E> node = validate(p);
if (numChildren(p) == 2) {
throw new IllegalArgumentException("p has two children");
}
Node<E> child = (node.getLeft() != null ? node.getLeft() : node.getRight());
if (child != null) {
child.setParent(node.getParent()); // child's grandparent becomes its parent
}
if (node == root) {
root = child; // child becomes root
} else {
Node<E> parent = node.getParent();
if (node == parent.getLeft()) {
parent.setLeft(child);
} else {
parent.setRight(child);
}
}
size--;
E temp = node.getElement();
node.setElement(null); // helps garbage collection
node.setLeft(null);
node.setRight(null);
node.setParent(node); // our convention for defunct node
return temp;
}
public String toString(Node<E> root) {
String result = "";
if (root != null) {
return "";
} else {
int depth = depth(root);
for (int i = 0; i < depth; i++) {
result = result + " ";
}
result = result + "-" + root.getElement().toString() + "\n";
result = result + toString(root.left);
result = result + toString(root.right);
}
return result;
}
} // ----------- end of LinkedBinaryTree class -----------
LinkedQueue.java
/** Realization of a FIFO queue as an adaptation of a SinglyLinkedList. All operations are performed in constant time. */
public class LinkedQueue<E> implements Queue<E> {
/** The primary storage for elements of the queue */
private SinglyLinkedList<E> list = new SinglyLinkedList<>(); // an empty list
/** Constructs an initially empty queue. */
public LinkedQueue() {
} // new queue relies on the initially empty list
/** Returns the number of elements in the queue. */
public int size() {
return list.size();
}
/** Tests whether the queue is empty. */
public boolean isEmpty() {
return list.isEmpty();
}
/** Inserts an element at the rear of the queue. */
public void enqueue(E element) {
list.addLast(element);
}
/** Returns, but does not remove, the first element of the queue. */
public E first() {
return list.first();
}
/** Removes and returns the first element of the queue. */
public E dequeue() {
return list.removeFirst();
}
/** Produces a string representation of the contents of the queue. (from front to back). This exists for debugging purposes only. */
public String toString() {
return list.toString();
}
}
Position.java
public interface Position<E> {
E getElement() throws IllegalStateException;
}
Queue.java
public interface Queue<E> {
/** Returns the number of elements in the queue. */
int size();
/** Tests whether the queue is empty. */
boolean isEmpty();
/** Inserts an element at the rear of the queue. */
void enqueue(E e);
/** Returns, but does not remove, the first element of the queue. */
E first();
/** Removes and returns the first element of the queue. */
E dequeue();
}
SinglyLinkedList.java
public class SinglyLinkedList<E> implements Cloneable {
// ---------------- nested Node class ----------------
/** Node of a singly linked list, which stores a reference to its element and to the subsequent node in the list (or null if this is the last node).
*/
private static class Node<E> {
/** The element stored at this node */
private E element; // reference to the element stored at this node
/** A reference to the subsequent node in the list */
private Node<E> next; // reference to the subsequent node in the list
/** Creates a node with the given element and next node. */
public Node(E e, Node<E> n) {
element = e;
next = n;
}
// Accessor methods
/** Returns the element stored at the node. */
public E getElement() {
return element;
}
/** Returns the node that follows this one (or null if no such node). */
public Node<E> getNext() {
return next;
}
// Modifier methods
/** Sets the node's next reference to point to Node n. */
public void setNext(Node<E> n) {
next = n;
}
} // ----------- end of nested Node class -----------
// instance variables of the SinglyLinkedList
/** The head node of the list */
private Node<E> head = null; // head node of the list (or null if empty)
/** The last node of the list */
private Node<E> tail = null; // last node of the list (or null if empty)
/** Number of nodes in the list */
private int size = 0; // number of nodes in the list
/** Constructs an initially empty list. */
public SinglyLinkedList() {
} // constructs an initially empty list
// access methods
/** Returns the number of elements in the linked list. */
public int size() {
return size;
}
/** Tests whether the linked list is empty. */
public boolean isEmpty() {
return size == 0;
}
/** Returns (but does not remove) the first element of the list. */
public E first() { // returns (but does not remove) the first element
if (isEmpty())
return null;
return head.getElement();
}
/** Returns (but does not remove) the last element of the list. */
public E last() { // returns (but does not remove) the last element
if (isEmpty())
return null;
return tail.getElement();
}
// update methods
/** Adds an element to the front of the list. */
public void addFirst(E e) { // adds element e to the front of the list
head = new Node<>(e, head); // create and link a new node
if (size == 0)
tail = head; // special case: new node becomes tail also
size++;
}
/** Adds an element to the end of the list. */
public void addLast(E e) { // adds element e to the end of the list
Node<E> newest = new Node<>(e, null); // node will eventually be the tail
if (isEmpty())
head = newest; // special case: previously empty list
else
tail.setNext(newest); // new node after existing tail
tail = newest; // new node becomes the tail
size++;
}
/** Removes and returns the first element of the list. */
public E removeFirst() { // removes and returns the first element
if (isEmpty())
return null; // nothing to remove
E answer = head.getElement();
head = head.getNext(); // will become null if list had only one node
size--;
if (size == 0)
tail = null; // special case as list is now empty
return answer;
}
public boolean equals(Object o) {
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
SinglyLinkedList other = (SinglyLinkedList) o; // use nonparameterized type
if (size != other.size)
return false;
Node walkA = head; // traverse the primary list
Node walkB = other.head; // traverse the secondary list
while (walkA != null) {
if (!walkA.getElement().equals(walkB.getElement()))
return false; // mismatch
walkA = walkA.getNext();
walkB = walkB.getNext();
}
return true; // if we reach this, everything matched successfully
}
public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
// always use inherited Object.clone() to create the initial copy
SinglyLinkedList<E> other = (SinglyLinkedList<E>) super.clone(); // safe cast
if (size > 0) { // we need independent chain of nodes
other.head = new Node<>(head.getElement(), null);
Node<E> walk = head.getNext(); // walk through remainder of original list
Node<E> otherTail = other.head; // remember most recently created node
while (walk != null) { // make a new node storing same element
Node<E> newest = new Node<>(walk.getElement(), null);
otherTail.setNext(newest); // link previous node to this one
otherTail = newest;
walk = walk.getNext();
}
}
return other;
}
public int hashCode() {
int h = 0;
for (Node walk = head; walk != null; walk = walk.getNext()) {
h ^= walk.getElement().hashCode(); // bitwise exclusive-or with element's code
h = (h << 5) | (h >>> 27); // 5-bit cyclic shift of composite code
}
return h;
}
/** Produces a string representation of the contents of the list. This exists for debugging purposes only. */
public String toString() {
StringBuilder sb = new StringBuilder("(");
Node<E> walk = head;
while (walk != null) {
sb.append(walk.getElement());
if (walk != tail)
sb.append(", ");
walk = walk.getNext();
}
sb.append(")");
return sb.toString();
}
}
Tree.java
import java.util.Iterator;
/** An interface for a tree where nodes can have an arbitrary number of children. */
public interface Tree<E> extends Iterable<E> {
Position<E> root();
Position<E> parent(Position<E> p) throws IllegalArgumentException;
Iterable<Position<E>> children(Position<E> p) throws IllegalArgumentException;
int numChildren(Position<E> p) throws IllegalArgumentException;
boolean isInternal(Position<E> p) throws IllegalArgumentException;
boolean isExternal(Position<E> p) throws IllegalArgumentException;
boolean isRoot(Position<E> p) throws IllegalArgumentException;
int size();
boolean isEmpty();
Iterator<E> iterator();
Iterable<Position<E>> positions();
}
and this is my driver that i have tried and struggled with!!
when i run the output for the tree is not what i am expected~~
Tree
-----
LinkedBinaryTree#5caf905d
PartA_Driver.java
import java.util.Scanner;
public class PartA_Driver {
public static void main(String[] args) {
// Output should look like
// - A |A|
// - B / \
// - C |B| |C|
// - D / \
// - E |D| |E|
// - F / \
// - G |F| |G|
LinkedBinaryTree<String> tree = new LinkedBinaryTree<>();
Position<String> A = tree.addRoot("Are you nervous?");
Position<String> B = tree.addLeft(A, "Saving Account.");
Position<String> C = tree.addRight(A, "Will you need to access most of the money within the next 5 years?");
Position<String> D = tree.addLeft(C, "Money market fund.");
Position<String> E = tree.addRight(C, "Are you willing to accept risks in exchange for higher expected returns?");
Position<String> F = tree.addLeft(E, "Stock portfolio.");
Position<String> G = tree.addRight(E, "Diversified portfolio with stocks, bonds, and short-term instruments.");
System.out.println("Tree\n-----");
System.out.println(tree.toString() + "\n");
// Are you nervous?
// Yes/ \No
// Saving Account. Will you need to access most of the
// money within the next 5 years?
// Yes/ \No
// Money market fund. Are you willing to accept risks in
// exchange for higher expected returns?
// Yes/ \No
// Stock portfolio. Diversified portfolio with stocks,
// bonds, and short-term instruments.
Scanner scanner = new Scanner(System.in);
System.out.println("Are you nervous? (yes/no)");
String decision = scanner.nextLine();
if (decision.equalsIgnoreCase("yes")) {
System.out.println("Saving Account.");
} else {
System.out.println("Will you need to access most of the money within the next 5 years? (yes/no)");
decision = scanner.nextLine();
if (decision.equalsIgnoreCase("yes")) {
System.out.println("Money market fund.");
} else {
System.out.println("Are you willing to accept risks in exchange for higher expected returns? (yes/no)");
decision = scanner.nextLine();
if (decision.equalsIgnoreCase("yes")) {
System.out.println("Stock portfolio.");
} else {
System.out.println("Diversified portfolio with stocks, bonds, and short-term instruments.");
}
}
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am having some issues with my linked list class. I am currently trying to print my favorite bands in the assigned order I gave them, but I am either coming up with the program just prints null or just the band names in the wrong order. I am confused as to why or what I am missing. Any help would be appreciated.
The output I currently get is
Exception in thread "main" java.lang.NullPointerException
at project2.jacobLinkedList.toString(MetalMasher.java:171)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at project2.MetalMasher.main(MetalMasher.java:44)
The file is
import java.util.Collections;
import java.util.List;
public class MetalMasher {
public static jacobLinkedList jacobList;
#SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
// this is the default constructor.
jacobList = new jacobLinkedList();
// add elements to the list.
jacobList.add("MegaDeth",1993);
jacobList.add("Slayer",1992);
jacobList.add("Scar Symmetry",2002);
jacobList.add("Gojira",2004);
jacobList.add("Amon Amarth",1997);
System.out.println("Print: jacobList:" + jacobList);
System.out.println(".size():" + jacobList.size());
System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
}
}
class jacobLinkedList {
private static int counter;
private Node head;
// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
// crawl to the requested index or the last element in the list, whichever comes first
for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
jacobCurrent = jacobCurrent.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
jacobTemp.setNext(jacobCurrent.getNext());
// reference to new node
jacobCurrent.setNext(jacobTemp);
// increment the number of elements variable
incrementCounter();
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node jacobCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (jacobCurrent.getNext() == null)
return false;
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
// returns the number of elements in this list.
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node jacobCurrent = head.getNext();
while (jacobCurrent != null) {
output += "[" + jacobCurrent.getData().getClass() + "]";
jacobCurrent = jacobCurrent.getNext();
}
}
return output;
}
public class Node {
// reference to the next node in the chain
Node next;
Object data;
// Node constructor
public Node(Object dataValue, Class<Integer> class1) {
next = (Node) null;
data = dataValue;
}
// Node contructor to point towards
#SuppressWarnings("unused")
public Node(Object dataValue, Node ranking) {
next = ranking;
data = dataValue;
}
public Node(Object data, int i) {
// TODO Auto-generated constructor stub
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
From the looks of it, it's most likely the getData method in the Node object that is returning null. That's because you forgot to set the data in the constructor with an object and integer.
public Node(Object data, int i) {
this.data = data;
}
I don't know what the integer is for though.
in toString() method in this line:
output += "[" + jacobCurrent.getData().getClass() + "]";
You need to check when getData() returns null, which it does in most cases for your inputs.
Solution is to check for null before adding string to output. Don't know what you want with it, either add string "null" or skip such cases or fix inputs.
Use:
/**
* Created by MR on 4/27/2016.
*/
import java.util.Collections;
import java.util.List;
public class Test {
public static jacobLinkedList jacobList;
#SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
// this is the default constructor.
jacobList = new jacobLinkedList();
// add elements to the list.
jacobList.add("MegaDeth",1993);
jacobList.add("Slayer",1992);
jacobList.add("Scar Symmetry",2002);
jacobList.add("Gojira",2004);
jacobList.add("Amon Amarth",1997);
System.out.println("Print: jacobList:" + jacobList);
System.out.println(".size():" + jacobList.size());
System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
}
}
class jacobLinkedList {
private static int counter;
private Node head;
// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
// crawl to the requested index or the last element in the list, whichever comes first
for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
jacobCurrent = jacobCurrent.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
jacobTemp.setNext(jacobCurrent.getNext());
// reference to new node
jacobCurrent.setNext(jacobTemp);
// increment the number of elements variable
incrementCounter();
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node jacobCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (jacobCurrent.getNext() == null)
return false;
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
// returns the number of elements in this list.
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node jacobCurrent = head.getNext();
while (jacobCurrent.getData() != null) {
output += "[" + jacobCurrent.getData().getClass() + "]";
jacobCurrent = jacobCurrent.getNext();
}
}
return output;
}
public class Node {
// reference to the next node in the chain
Node next;
Object data;
// Node constructor
public Node(Object dataValue, Class<Integer> class1) {
next = (Node) null;
data = dataValue;
}
// Node contructor to point towards
#SuppressWarnings("unused")
public Node(Object dataValue, Node ranking) {
next = ranking;
data = dataValue;
}
public Node(Object data, int i) {
// TODO Auto-generated constructor stub
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
I hope this helps you
This is the initial class provided which we cannot modify
public class SLL {
public class Node {
private int data;
private Node next;
public Node() {
data = 0;
next = null;
}
public Node(int newData, Node linkValue) {
data = newData;
next = linkValue;
}
public int getData() {
return data;
}
public Node getLink() {
return next;
}
}// End of Node inner class
private Node head;
public SLL() {
head = null;
}
public void addToStart(int itemData) {
head = new Node(itemData, head);
}
public boolean contains(int item) {
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a reference
* to that node. If target is not in the list, null is returned.
*/
public Node find(int target) {
Node position = head;
int itemAtPosition;
while (position != null) {
itemAtPosition = position.data;
if (itemAtPosition == target) {
return position;
}
position = position.next;
}
return null; // target was not found
}
public void outputList() {
Node position = head;
while (position != null) {
System.out.print(position.data + " ");
position = position.next;
}
System.out.println();
}
}
And this is the Set class that we are supposed to finish to get the Tester to work and I keep getting a Null Pointer Exception with my add method, however, it is almost exactly as I have seen in other codes including our text book. Any insight would be very much appreciated as my instructor has pre-made powerpoints and doesn't explain anything or offer any advice to students seeking help.
public class Set {
private SLL[] hashArray; // DO NOT MODIFY THIS LINE
private int size = 10; // DO NOT MODIFY THIS LINE
// DO NOT MODIFY THIS METHOD
public Set() {
hashArray = new SLL[size];
}
// DO NOT MODIFY THIS METHOD
private int computeHash(int s) {
return s % size;
}
// COMPLETE BELOW
public void add(int x)
{
int hash = computeHash(x); // Get hash value
SLL list = hashArray[hash];
if (!list.contains(x))
{
// Only add the target if it's not already
// on the list.
list.addToStart(x);/*replaced hashArray[hash] with list*/
}
}
public void output( )
{
System.out.println("I will work on this later");
}
}
Finally, the Tester...
public class Tester{
// Have this method to display your name, instead.
static void displayName(){
System.out.println("Program written by Tony.\n");
}
// DO NOT MODIFY THE MAIN METHOD
public static void main(String[] args){
displayName();
Set set1 = new Set();
Set set2 = new Set();
set1.add(3);
set1.add(3);
set1.add(13);
set1.add(23);
set1.add(4);
set1.add(5);
set2.add(15);
set2.add(6);
set2.add(6);
System.out.println("Contents of set 'set1': ");
set1.output();
System.out.println("Contents of set 'set2': ");
set2.output();
System.out.println();
}
}
I don't want to give the answer directly as this is likely a homework assignment (correct me if I am wrong). Consider the very first time the add method is called on a newly constructed set. What values are in all indices of "hashArray" at this time and what does that mean for the local variable "list" in your add method?
This line isn't doing what you think it's doing.
hashArray = new SLL[size];
You need to actually create each SLL that will populate the array once the array itself is created.
Okay, so I'm trying to create my own LinkedList class (with generic typing) in Java but am running into problems. I have created a LinkedListNode class which basically sets and gets the next and right pointers and also the node's key. My LinkedList class code is posted below, if you compile and run you'll see it's not setting the list up as it should. At the moment, I am trying to insert node y after node x, but my printout looks like:
Key: 5 - prev key: 6 - next key: 6
Key: 6 - prev key: null - next key: null
My code:
public class LinkedList<T> {
private LinkedListNode<T> m_head = null;
private LinkedListNode<T> m_tail = null;
public LinkedList() {
m_head = new LinkedListNode<T>();
m_tail = new LinkedListNode<T>();
m_head.setNext(m_tail);
m_tail.setPrev(m_head);
}
public LinkedListNode<T> getHead() {
return m_head;
}
public LinkedListNode<T> getTail() {
return m_tail;
}
public void insert(LinkedListNode<T> node, LinkedListNode<T> prev_node) {
prev_node.getNext().setPrev(node);
node.setPrev(prev_node);
node.setNext(prev_node.getNext());
prev_node.setNext(node);
}
public void delete(LinkedListNode<T> node) {
}
#Override
public String toString() {
LinkedListNode<T> pointer = m_head.getNext();
String result = "";
while(pointer.getKey() != null) {
T prev_key = pointer.getPrev() == null ? null : pointer.getPrev().getKey();
T next_key = pointer.getNext() == null ? null : pointer.getNext().getKey();
result += "\nKey: " + pointer.getKey() + " - prev key: " + prev_key + " - next key: " + next_key;
pointer = pointer.getNext();
}
return result;
}
public static void main(String[] args) {
LinkedListNode<Integer> x = new LinkedListNode<Integer>(5);
LinkedListNode<Integer> y = new LinkedListNode<Integer>(6);
LinkedList<Integer> list = new LinkedList<Integer>();
list.insert(x, list.getHead());
list.insert(y, x);
System.out.println(list.toString());
}
}
LinkedListNode.java:
public class LinkedListNode<T> {
private T m_key;
private LinkedListNode<T> m_next = null;
private LinkedListNode<T> m_prev = null;
public LinkedListNode() {
}
public LinkedListNode(T key) {
m_key = key;
}
public T getKey() {
return m_key;
}
public void setKey(T key) {
m_key = key;
}
public LinkedListNode<T> getNext() {
return m_next;
}
public LinkedListNode<T> getPrev() {
return m_next;
}
public void setNext(LinkedListNode<T> node) {
m_next = node;
}
public void setPrev(LinkedListNode<T> node) {
m_prev = node;
}
}
What you try to implement is Double Linked List (double as you have next and previous).
And you have a problem in your structure design, maintain the head and tail can be issue prone.
You should try to implement it using single element that refer to other.
LinkedListNode<T> header = new LinkedListNode<T>();
header.getNext(); // head
header.getPrevious()//tail
The example of insert
public void insert(T element) { //We add to the begin
LinkedListNode<T> newElement = LinkedListNode<T>(element);
newElement.setNext(header); //previous begin we set to be next
newElement.setPrevious(header.getPrevious()); //previous end we set to be end.
newElement.getPrevious().setNext(newElement); //to previous end we set new begin.
newElement.getNext().setPrevious(newElement); //to previous begin we set new end.
}