Java: Generic Class Exception - java

I was designing a generic linked list to create a linked list of Strings.
However I keep getting this error :
Exception in thread "main" java.lang.NoSuchMethodError: Node.<init>(Ljava/lang/Object;)V
at LinkedList.addNode(LinkedList.java:10)
at LinkedList.<init>(LinkedList.java:22)
at Trial.main(Trial.java:7)
From the stack trace , the error is generated at LinkedList's addNode() method. Im including the definition to this method as well as the definition of the Node class.
LinkedList addNode()
public void addNode(T n) {
Node<T> temp = new Node<T>(n);
if(start==null) {
start = temp;
current = start;
} else {
end.setNext(temp);
}
end =temp;
}
Node.java
public class Node<T>{
private T n;
Node next;
Node(T n) {
this.n = n;
next = null;
}
public void setNext(Node nextNode) {
next = nextNode;
}
public Node getNext() {
return next;
}
public T getN() {
return n;
}
#Override
public String toString() {
if(n instanceof String)
return n.toString();
else {
return T.toString();
}
}
}
LinkedList.java
public class LinkedList<T>{
Node start;
Node end;
Node current;
private static final long serialVersionUID = 901L;
LinkedList(T n) {
addNode(n);
}
public void addNode(T n) {
Node<T> temp = new Node<>(n);
if(start==null) {
start = temp;
current = start;
} else {
end.setNext(temp);
}
end =temp;
}
LinkedList(T[] n) {
for(T print : n)
addNode(print);
}
public void addNode(T[] n) {
if(n!=null) {
for (T values : n) {
addNode(values);
}
}
}
public void incC() {
current = current.getNext();
}
public void insert(T n) {
Node newNode = new Node(n);
if(current==start){
newNode.setNext(current);
start = newNode;
}else {
Node tempstart = start;
Node prevAdd=null;
while(tempstart!=current){
prevAdd = tempstart;
tempstart = tempstart.getNext();
}
prevAdd.setNext(newNode);
newNode.setNext(current);
}
}
public void find(T x) {
Node tempstart;
tempstart = start;
while (tempstart!=null) {
if(tempstart.getN()==x) {
System.out.println("Element found");
tempstart = tempstart.getNext();
} else {
tempstart = tempstart.getNext();
}
}
}
public void delete(T x) {
Node previous=null;
Node tempstart = start;
while(tempstart!=null) {
if(tempstart.getN()==x) {
if(previous ==null) {
previous = tempstart;
tempstart = tempstart.getNext();
start = tempstart;
previous.setNext(null);
previous = null;
} else {
tempstart = tempstart.getNext();
previous.setNext(tempstart);
}
}else {
previous = tempstart;
tempstart = tempstart.getNext();
}
}
}
#Override
public String toString() {
Node tempNode = start;
String str = "Values: ";
while (tempNode!=null) {
str = str + " " + tempNode.toString();
tempNode = tempNode.getNext();
}
return str;
}
}
Trial.java
public class Trial {
public static void main(String[] args) {
String[] para = {"Hollo","this","is","me"};
LinkedList<String> L1;
L1 = new LinkedList<String>(para);
System.out.println(L1);
}

return T.toString();
this doesn't work. T is a type variable and only available at compile time due to type erasure.
But apart from that, I can't see what's wrong, you need to poost more code from your LinkedList class.

You should declare the start, end, and current fields in LinkedList< T > and the next field in Node< T > as type Node< T >, not Node. Don't use raw types anywhere in the code, because they translate into Node< Object >.

Your class Nodedoes not compile, so it is likely that you should first fix that issue before continuing:
return T.toString();
does not make sense. Probably that just writing this:
return n.toString();
is enough for now.

In Node.java, in the method
#Override
public String toString() {
if(n instanceof String)
return n.toString();
else {
return T.toString();
}
}
// the below statement thows compilation error.
return T.toString();

Your Node Constructor is not public, so it will not work if you call it from a class in another package.

Related

How to extend child classes with a parent interface class

interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?

java linked list compare with first element and remove using peek() method

created java linked list to add some data. want to compare first data inside that linked list. when i use peek() it not working. any other way to get front element and compare or how to write peek() method
LinkList class :
package list;
public class LinkList {
private class Node<T> {
public final T data;
public Node next;
public Node(T data) {
this.data = data;
}
public void displayNode() {
System.out.print(data + " ");
}
}
public static Node first = null;
private Node last = null;
public boolean isEmpty() {
return (first == null);
}
public <T> void addLast(T data) {
Node n = new Node(data);
if (isEmpty()) {
n.next = first;
first = n;
last = n;
} else {
last.next = n;
last = n;
last.next = null;
}
}
public void removeFirst() {
Node temp = first;
if (first.next == null) {
last = null;
}
first = first.next;
}
public void displayList() {
Node current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
}
}
LinkListQueue:
package list;
public class LinkListQueue {
LinkList newLinkList = new LinkList();
public <T> void enqueue(T data) {
newLinkList.addLast(data);
}
public void dequeue() {
if (!newLinkList.isEmpty()) {
newLinkList.removeFirst();
}
}
public String displayQueue() {
newLinkList.displayList();
System.out.println();
return "";
}
public boolean isEmpty() {
return newLinkList.isEmpty();
}
}
LinkListQueueMain :
package list;
public class LinkListqueueMain {
public String getValue=null;
public static String displayQ = null;
static LinkListQueue queueImpl = new LinkListQueue();
static LinkList linkList = new LinkList();
public static void main(String[] args) {
runData();
}
public static void runData() {
queueImpl.enqueue("80%");
queueImpl.enqueue("70%");
queueImpl.enqueue("60%");
queueImpl.enqueue("85%");
queueImpl.enqueue("45%");
queueImpl.enqueue("55%");
for (int i = 0; i < 5; i++) {
System.out.println(linkList.toString());
}
}
}
This is my code. Any idea how to do that?
First you need to paramtrize the LinkList, not necessarily the node, as the LinkList is the public API to the outer world.
public class LinkList<T> {
private static class Node {
Then you could return the removed value. (removeFirst can throw a NullPointerException on an empty list.)
public T removeFirst() {
T removed = first.data;
if (first.next == null) {
last = null;
}
first = first.next;
return removed;
}
public T peekFirst() {
return first.data;
}

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
}}

java.lang.NullPointerException in my custom class

I wish to implement a Queue based in a simple linked list class, without using java.util.
When I call the addEnd method in List class through enqueue method, I receive a java.lang.NullPointerException, though I expect the second element.
Which solution can I take?
The node class
public class Node {
private int value;
private Node next;
public Node(int val) {
value = val;
}
public Node(int val, Node next) {
value = val;
this.next=next;
}
public Node(Node next) {
this.next=next;
}
public int getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public void displayNode() {
System.out.print(" "+value+" ");
}
}
My interface
public interface MyQueue {
void enqueue(int oVal);
int dequeue();
}
The List
public class List {
private Node first;
private Node last;
private int counter;
public List() {
first = null;
last = null;
}
public boolean isEmpty() {
return first==null;
}
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first = n1;
} else {
last.setNext(n1);
last = n1;
}
}
public int deleteStart() {
int temp = first.getValue();
if(first.getNext() == null){
last = null;
first = first.getNext();
}
return temp;
}
public void displayList() {
Node current = first;
while(current != null) {
current.displayNode();
current = current.getNext();
}
System.out.println("");
}
public int size() {
return counter;
}
}
The Queue
public class Queue implements MyQueue {
private List listQ;
public Queue() {
listQ = new List();
}
public boolean isEmpty() {
return listQ.isEmpty();
}
public void enqueue(int oVal) {
listQ.addEnd(oVal);
}
public int dequeue() {
return listQ.deleteStart();
}
public void displayQueue() {
System.out.print("Queue ");
listQ.displayQueue();
}
}
public class App {
public static void main(String[] args) {
Queue q1 = new Queue();
System.out.println("Two insertions");
q1.enqueue(4);
q1.enqueue(64);
q1.displayQueue();
System.out.println("Insert at the end : ");
q1.enqueue(23);
q1.displayQueue();
System.out.println("Delete an element at the begining of the queue");
q1.dequeue();
q1.displayQueue();
}
}
What #pens-fan-69 said is true. I'd like to add on to that. In order to make your code work, all you have to do is make sure last is set to first during the first insert:
public void addEnd(int val) {
Node n1 = new Node(val);
if( isEmpty() ) {
first=last=n1;
} else {
last.setNext(n1);
last = n1;
}
}
I tried running the code in online compiler and it works: http://goo.gl/99FyfY
You need to set the last reference when inserting to the empty list. The NullPointerException is because you use last before ever setting it.

Error at Linked list (java)

I created my own linked list, but when I tried to run it there is an error:
Exception in thread "main" java.lang.NullPointerException
at List.add(List.java:8) //if(t.val ==null)
at main.main(main.java:38) //linput.add(inputLine.split(" ")[i]);
Here is my List class:
class List{
String val;
List next=null;
private List t;
public void add(String word){
if(t.val ==null)
t.val=word;
else while(!t.next.val.equals(null))
{
t=t.next;
if(t.next.val.equals(null))
{
t.next.val=word;
break;
}
}
}
public int get(String word)
{
int i=0;
if(t.val.equals(word))
i=0;
else while(!t.next.val.equals(word))
{
t=t.next;
i++;
if(t.next.val.equals(word))
{
i++;
}
}
return i;
}
public String indexOf(int i)
{
int counter=0;
while(counter<i)
{
t=t.next;
counter++;
}
return t.val;
}
}
And here is my main function :
static public void main(String[] args)
{
List linput = new List();
String inputLine = "Hey look at me.";
for(int i = 0 ; i < inputLine.split(" ").length ; i++)
{
linput.add(inputLine.split(" ")[i]);
}
System.out.println(linput.indexOf(0)+" "+linput.indexOf(1)+" "+linput.indexOf(2));
}
I initialized t but next time there is an error like this:
private List t =new List();
Exception in thread "main" java.lang.StackOverflowError
at List.<init>(List.java:5)
at List.<init>(List.java:5)
at List.<init>(List.java:5)
Sorry. I can't give my full code, because the rest of my code is working well (reading from txt etc....).
The error seems to be related to the variable 't' (i.e., private List t).
Did you initialize this variable ? The if (t.val == null) seems to be cribbing this as t is null (uninitialized) at this point
You should have allocated object (using new) for this variable.
Can you share the full code for the constructor of List ?
Assuming you want to implement a simple forward list, rather than use the Java LinkedList class, you need to:
Change your implementation of the list to reference nodes in the list
handle traversal of the linked nodes in your word list
Here is an example:
WordList class
package com.example.words;
class WordList {
private WordNode head = null;
private int listSize = 0;
public void add(String word) {
// TODO add check for duplicate word
if (head == null) {
head = new WordNode();
head.setValue(word);
listSize++;
} else {
WordNode current = head;
while (current.getNext() != null) {
current = current.getNext();
}
WordNode newNode = new WordNode();
newNode.setValue(word);
current.setNext(newNode);
listSize++;
}
}
public int getWordIndex(String word) {
WordNode current = head;
int index = 0;
boolean found = false;
while (!found && current != null) {
found = current.getValue().equalsIgnoreCase(word);
if (!found) {
index++;
current = current.getNext();
}
}
if (found) {
return index;
} else {
return -1;
}
}
public String indexOf(int i) {
int index = 0;
WordNode current = head;
if (i <= listSize) {
while (index < i) {
current = current.getNext();
index++;
}
return current.getValue();
} else {
return null;
}
}
public int size() {
return listSize;
}
}
WordNode Class
package com.example.words;
public class WordNode {
private String value;
private WordNode next = null;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public WordNode getNext() {
return next;
}
public void setNext(WordNode link) {
next = link;
}
}
Test Driver
package com.example.words;
public class Test {
public static void main(String[] args) {
//TODO handle punctuation
WordList myList = new WordList();
String inputLine = "Hey look at me.";
String[] pieces = inputLine.split(" ");
for (int i=0; i < pieces.length; i++) {
myList.add(pieces[i]);
}
for (int i=0; i < pieces.length; i++) {
String value = myList.indexOf(i);
if (value.equalsIgnoreCase(pieces[i])) {
System.out.println("Following node is wrong:");
}
System.out.println ("node " + i + ". = " + value);
}
}
}
You tried to create t as a member variable of its own class like this:
class List {
[...]
private List t = new List();
[...]
}
This won't work because the constructor of List would be called indefinitely.
Try lazy instantiation of t instead. Replace all access of t with a getter:
private List getT() {
if (this.t == null) {
this.t = new List();
}
return t;
}

Categories

Resources