LinkedList class. (ReflectiveOperationException) - java

I am learning Java SE and am currently at simple linked lists (page 687/1047 of Savitch's Absolute Java).
I am stuck at instantiating the LinkList in the main method of my demo class:
LinkedList1 list = new LinkedList1();
I tried using breakpoint and it indicates a ReflectiveOperationException.
This is the code:
public class Node1
{
private String item;
private int count;
private Node1 link;
public Node1()
{
link = null;
item = null;
count = 0;
}
public Node1(String newItem, int newCount, Node1 linkValue)
{
setData(newItem, newCount);
link = linkValue;
}
public void setData(String newItem, int newCount)
{
item = newItem;
count = newCount;
}
public void setLink(Node1 newLink)
{
link = newLink;
}
public String getItem()
{
return item;
}
public int getCount()
{
return count;
}
public Node1 getLink()
{
return link;
}
}
This is the LinkedList1 class:
public class LinkedList1
{
private Node1 head;
public LinkedList1()
{
head = null;
}
/**
* Adds a node at the start of the list with the specified data.
* The added node will be the first node in the list.
*/
public void add(String itemName, int itemCount)
{
head = new Node1(itemName, itemCount, head);
}
/**
* Removes the head node and returns true if the list contains at least
* one node. Returns false if the list is empty.
*/
public boolean deleteHeadNode()
{
if (head != null)
{
head = head.getLink();
return true;
}
else
return false;
}
/**
* Returns the number of nodes in the list.
*/
public int size()
{
int count = 0;
Node1 position = head;
while (position != null)
{
count++;
head = position.getLink();
}
return count;
}
public boolean contains(String item)
{
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a
* reference to that node. If the target is not in the list, null is returned.
*/
public Node1 find(String target)
{
Node1 position = head;
String itemAtPosition;
while(position != null)
{
itemAtPosition = position.getItem();
if(itemAtPosition.equals(target))
{
return position;
}
position = position.getLink();
}
return null; //target was not found
}
public void outputList()
{
Node1 position = head;
while (position != null)
{
System.out.println(position.getItem() + " " + position.getCount());
position = position.getLink();
}
}
}
I think that the problem has something to do with the constructor of Node1 having the member link of type Node1. I'm trying to understand how these data structures work and not just resort to using the built-in ArrayList(& APIs) for my projects. Can you guys have a look and point me in the right direction. Any help would be very much appreciated.
This is my main method.
public class LinkedListDemo
{
public static void main(String[] args)
{
try
{
LinkedList1 list = new LinkedList1();
list.add("apples", 1);
list.add("bananas", 2);
list.add("cantaloupe", 3);
System.out.println("List has "+ list.size() + " nodes.");
list.outputList();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Your size method contains an infinite loop which explain why the outputs are never reached.
while (position != null)
{
count++;
head = position.getLink();
}
You are looping until position is null, but never assign anything to position and instead assign to head. Instead, you want to do
while (position != null)
{
count++;
position = position.getLink();
}
Now you would get the output
List has 3 nodes.
cantaloupe 3
bananas 2
apples 1

Related

Java linked list how to make a private method to handle searching

I trying and need help on how to create a private method to search a singly linked list.
My private search method is all the way at the bottom, how can I create a private method so i can then use it in an add/delete method?
I have been trying to do this for hours and I can't seem to get it right, i want to make a private search method to avoid loops later on in my other methods such as find add delete
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}
You can create a search method in a single linked list which returns the position of the item or e.g. -1 in case the item was not found.
This search method will need to loop from the first node through its tailing nodes sequentially, extracts the item associated to each node and uses the equals method to try to find a match with the search item.
Here is a possible implementation in Java:
public int search(T item) {
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
Below is a full example of how you can do it in a simple linked list with minimal generics support. Included is also a main method with a minimal unit test to prove the concept:
public class LinkedBag<T> {
private Node first;
private int n;
public LinkedBag() {
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void add(T item) {
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
n++;
}
public int search(T item) {
if(item == null) {
throw new IllegalArgumentException("Cannot search null");
}
Node x = first;
int c = size() - 1;
while(x != null) {
if(x.item.equals(item)) {
return c;
}
x = x.next;
c--;
}
return -1;
}
private class Node {
private T item;
private Node next;
}
public static void main(String[] args) {
LinkedBag<Integer> intBag = new LinkedBag<>();
intBag.add(1);
intBag.add(2);
intBag.add(3);
System.out.println(intBag.search(1) == 0);
System.out.println(intBag.search(2) == 1);
System.out.println(intBag.search(3) == 2);
System.out.println(intBag.search(4) == -1);
}
}

Java: Converting a single-linked list into a doubly linked list from scratch

This is for a class assignment; I currently have a single-linked list and need to convert it into a doubly-linked list. Currently, the list is a collection of historical battles.
What in this program needs to be changed to turn this into a double-linked list? I feel like I'm really close, but stuck on a certain part (What needs to be changed in the 'add' part)
public static MyHistoryList HistoryList;
public static void main(String[] args) {
//Proof of concept
HistoryList = new MyHistoryList();
HistoryList.add("Battle of Vienna");
HistoryList.add("Spanish Armada");
HistoryList.add("Poltava");
HistoryList.add("Hastings");
HistoryList.add("Waterloo");
System.out.println("List to begin with: " + HistoryList);
HistoryList.insert("Siege of Constantinople", 0);
HistoryList.insert("Manzikert", 1);
System.out.println("List following the insertion of new elements: " + HistoryList);
HistoryList.remove(1);
HistoryList.remove(2);
HistoryList.remove(3);
System.out.println("List after deleting three things " + HistoryList);
}
}
class MyHistoryList {
//setting up a few variables that will be needed
private static int counter;
private Node head;
This is the private class for the node, including some getters and setters. I've already set up 'previous', which is supposed to be used in the implementation of the doubly-linked list according to what I've already googled, but I'm not sure how to move forward with the way MY single-list is set up.
private class Node {
Node next;
Node previous;
Object data;
public Node(Object dataValue) {
next = null;
previous = null;
data = dataValue;
}
public Node(Object dataValue, Node nextValue, Node previousValue) {
previous = previousValue;
next = nextValue;
data = dataValue;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getprevious() {
return previous;
}
public void setprevious(Node previousValue) {
previous = previousValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
This adds elements to the list. I think I need to change this part in order to make this into a doubly-linked list, but don't quite understand how?
public MyHistoryList() {
}
// puts element at end of list
public void add(Object data) {
// just getting the node ready
if (head == null) {
head = new Node(data);
}
Node Temp = new Node(data);
Node Current = head;
if (Current != null) {
while (Current.getNext() != null) {
Current = Current.getNext();
}
Current.setNext(Temp);
}
// keeping track of number of elements
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
This is just tostring, insertion, deletion, and a few other things. I don't believe anything here needs to be changed to make it a doubly linked list?
public void insert(Object data, int index) {
Node Temp = new Node(data);
Node Current = head;
if (Current != null) {
for (int i = 0; i < index && Current.getNext() != null; i++) {
Current = Current.getNext();
}
}
Temp.setNext(Current.getNext());
Current.setNext(Temp);
incrementCounter();
}
//sees the number of elements
public Object get(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
// removal
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node Current = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return false;
Current = Current.getNext();
}
Current.setNext(Current.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node Current = head.getNext();
while (Current != null) {
output += "[" + Current.getData().toString() + "]";
Current = Current.getNext();
}
}
return output;
}
}

Java linked list node print Error [duplicate]

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

Queue Scenario Help Getting Started

Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void print() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Node Class
public class Node<E>{
private E element;
private Node<E> next;
public Node(E element, Node next) {
this.element = element;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node<E> getNextNode() {
return next;
}
public E getElement() {
return element;
}
public String toString() {
return element.toString();
}
}
Simulation Class
import java.util.Random;
public class Simulation {
private int arrivalRate;
//you'll need other instance variables
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
}
public void runSimulation() {
//this is an example for using getRandomNumPeople
//you are going to remove this whole loop.
for (int i = 0; i < 10; i++) {
int numPeople = getRandomNumPeople(arrivalRate);
System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
}
}
//Don't change this method.
private static int getRandomNumPeople(double avg) {
Random r = new Random();
double L = Math.exp(-avg);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
//Don't change the main method.
public static void main(String[] args) {
Simulation s = new Simulation(18, 10);
s.runSimulation();
}
}
It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
// missing the handling of maxNumQueues
}
So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {
private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}

Null Pointer Exception with Singly Linked List to hashtable Java

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.

Categories

Resources