CircularlinkedList generics - java

I am experiencing a problem with generics in a CircularLinkedList. I have my CircularLinkedList class, a Node class and a Person class.
The Node's should contain persons and the CircularLinkedList should contain those nodes. The problem is, that when i try to create my CircularLinkedList in my Test class, i get an error saying:
Bound mismatch: The type Node<Person> is not a valid substitute for
the bounded parameter <E extends Comparable<? super E>> of the type
CircularLinkedList<E>
Can you take a look at my generics?
CircularLinkedList.java
package cirkulærliste;
import java.util.Random;
public class CircularLinkedList<E extends Comparable<? super E>> {
private Node<E> next;
private Node<E> start;
private int size = 0;
public CircularLinkedList() {
setNext(null);
}
/**
* tilføjer personer
* #param p
*/
public void addPerson(E e) {
Node<E> newNode = new Node<E>(e, null);
Node<E> tempNext = next;
if(next == null){
next = newNode;
next.setNext(next);
} else if(size > 1){
}
}
/**
* udskriver personerne i den rækkefølge de står i listen
*/
public void print() {
Node<E> tempNode = start;
while (!tempNode.getNext().equals(start)) {
System.out.println(tempNode);
tempNode = tempNode.getNext();
}
System.out.println(tempNode);
}
/**
* en tilfældig person i den cirkulæreliste vælges som start i listen
*/
public void randomStart() {
int size = 1;
Node<E> tempNode = next.getNext();
while (!tempNode.getNext().equals(next.getNext())) {
tempNode = tempNode.getNext();
size++;
}
Random randomizer = new Random();
int chosen = randomizer.nextInt(size);
for (int i = 0; i <= chosen; i++) {
tempNode = tempNode.getNext();
}
start = tempNode;
}
/**
* fjerner den person fra listen der ligger count pladser fra start i listen. Personen der fjernes returneres.
* #param count
*/
public Node<E> remove(int count) {
Node<E> tempNode2;
for (int i = 1; i < 5; i++) {
next = next.getNext();
}
tempNode2 = next.getNext();
next.setNext(next.getNext().getNext());
tempNode2.setNext(null);
return tempNode2;
}
public void setNext(Node<E> next) {
this.next = next;
}
public Node<E> getNext() {
return next;
}
public void setStart(Node<E> start) {
this.start = start;
}
public Node<E> getStart() {
return start;
}
}
Node.java
package cirkulærliste;
public class Node<E> {
private E element;
private Node<E> next;
public Node(){
element = null;
next = null;
}
public Node(E element, Node<E> next){
this.setElement(element);
this.next = next;
}
public E getElement() {
return element;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> newNode) {
this.next = newNode;
}
public String toString(){
return "" + element;
}
}
Person.java
package cirkulærliste;
public class Person implements Comparable<Person> {
private String name;
private int number;
public Person(String name, int number){
this.setName(name);
this.setNumber(number);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
return "Name: " + name + " - " + "Number: " + number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
#Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return 0;
}
}
Test.java
public class Test {
public static void main(String[] args) {
CircularLinkedList<Person> list = new CircularLinkedList<Person>();
Node<Person> n1 = new Node<Person>();
n1.setElement(new Person("Thomas", 1));
list.addPerson(n1); // Compile error occurs here
}
}

It sounds like you're writing
CircularLinkedList<Node<Person>>
in your Test class; but you actually need to be writing
CircularLinkedList<Person>
Update for updated question: You also need to change this:
Node<Person> n1 = new Node<Person>();
n1.setElement(new Person("Thomas", 1));
list.addPerson(n1); // Compile error occurs here
to this:
list.addPerson(new Person("Thomas", 1));
In general, code that uses CircularLinkedList shouldn't refer to Node; CircularLinkedList uses Node internally, but users of the class don't need to worry about that.
Also, it's kind of odd that your generic CircularLinkedList class has a method named addPerson. Surely it should be called addElement, or just add?

Putting your code into an IDE gives me an error here:
Node<Person> n1 = new Node<Person>();
n1.setElement(new Person("Thomas", 1));
list.addPerson(n1);
A method addPerson(E e) on a collection of type CircularLinkedList<Person> expects a Person instance as a parameter. Your implementation of addPerson even creates a new Node instance (as it should), so there's no need to do it in calling code.
This compiles fine:
list.addPerson(new Person("Thomas", 1));

Related

When I pass the Node variable that is "top" inside the node objects ? does it help it to point the previous data?

I am writing a code to practice some linked list example with basics but came across a problem when in linked list class in voidadd method what does it means when I pass the Node variable that is "top" inside the node objects ? does it help it to point the previous data? i have indicated the part that refers to my question
public class Node
{
private int data;
private Node nextNode;
public Node(int dataP , Node nextNodeP)
{
data = dataP;nextNode = nextNodeP;
}
public int getData()
{
return data;
}
public Node getNextNode()
{
return nextNode;
}
public void setData(int newData) //to replace the value of some notes [12| ] --> [120| ]
{
data = newData;
}
public void setNext(Node newNextNode) // pointing to top ---> [120| ] ---> [last | null]
{
nextNode = newNextNode;
}
}
public class LinkedList {
private Node top;
private int size;
public LinkedList() {
top = null;
size = 0;
}
public int getSize() {
return size;
}
public void addNode(int newData) {
Node temp = new Node(newData, top); //question
top = temp; //points to the same
size++;
}
}
Define a node at its own class.
Here is a simple example :
public class LinkedList {
private Node first,last;
private int size ;
//adds node as last. not null safe
public void addNode(Node node) {
if(first == null) {
node.setParent(null);
first = node;
last = node;
}else {
node.setParent(last);
last = node;
}
size++;
}
public Node getFirst() {return first;}
public Node getLast() { return last; }
public int getSize() {return size;}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.addNode(new Node(0,null));
list.addNode(new Node(1,null));
list.addNode(new Node(2,null));
list.addNode(new Node(3,null));
Node node = list.getLast();
System.out.println("list has "+ list.size + " nodes:");
while(node != null) {
System.out.println(node);
node = node.getParent();
}
}
}
class Node{
private int data;
private Node parent;
Node(int nodeData, Node parent) {
data = nodeData;
this.parent = parent;
}
public int getData() { return data;}
public void setData(int data) { this.data = data; }
public Node getParent() {return parent; }
public void setParent(Node parent) {this.parent = parent;}
#Override
public String toString() {return "Node "+getData() +" parent:"+ getParent();}
}

How to change the order of a single linkedlist queue in java?

public class Node<E> {
private E element;
public Node<E> next;
int data;
Node(int d)
{
data = d;
next = null;
}
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public Node<E> getNext() {
return next;
}
public void setElement(E element) {
this.element=element;
}
public void setNext(Node<E> n) {
next = n;
}
public void displayNode(){
System.out.print(element+ " ");
}
}
public class SinglyLinkedList<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public SinglyLinkedList() {
head = tail = null;
size = 0;
}
public SinglyLinkedList(Node<E> head, Node<E> tail) {
this.head = head;
this.tail = tail;
}
public Node<E> getHead() {
return head;
}
public Node<E> getTail() {
return tail;
}
public void setHead(Node<E> head) {
this.head = head;
}
public void setTail(Node<E> tail) {
this.tail = tail;
}
public boolean isEmpty() {
if (head == null) {
return true;
}
return false;
}
public E first() {
return head.getElement();
}
public E last() {
return tail.getElement();
}
public void addFirst(E e) {
if (head == null) {
head = tail = new Node(e, null);
} else {
Node<E> newest = new Node(e, head);
head = newest;
}
size++;
}
public void addLast(E e) {
if (tail == null) {
head = tail = new Node(e, null);
} else {
Node<E> newest = new Node(e, null);
tail.setNext(newest);
tail = newest;
}
size++;
}
public E removeFirst() {
E e = head.getElement();
head = head.getNext();
size--;
return e;
}
#Override
public String toString() {
Node<E> tmp = head;
String s = "";
while (tmp != null) {
s += tmp.getElement();
tmp=tmp.getNext();
}
return s;
}
public void displayList() {
Node current = head;
while (current != null) {
current.displayNode();
current = current.next;
}
}
}
public interface Queue<E> {
int size();
boolean isEmpty();
void enqueue( );
E first();
E dequeue();
}
public class LinkedQueue<E> implements Queue<E> {
private SinglyLinkedList<E> list = new SinglyLinkedList<>();
public LinkedQueue() {
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void enqueue(E element) {
list.addLast(element);
}
public E first() {
return list.first();
}
public E dequeue() {
return list.removeFirst();
}
#Override
public void enqueue() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools |list.addLast(element);
}
public void displayQueue() {
list.displayList();
System.out.println();
}
public class Main {
public static void main(String[] args) {
LinkedQueue list = new LinkedQueue();
list.enqueue(sam);
list.enqueue(adams);
list.enqueue(john);
list.enqueue(isac);
list.enqueue(gad);
System.out.print("\n Linked list before calling swapNodes() ");
list.displayQueue();
}}
How to change the order of these names in the queue?
I have try to put function that swap nodes in the singlylinkedlist class but it didn't work.i m confused in which layer should i make this function in the linkedqueue class or the singlylinkedlist class or in the main class. yes i want just to swap names in the queue as simple as that.
UPDATED ANSWER
I modified your Node and NodeList Classes in a way which is easier to understand. I also kept similar private values and similar methods for those classes.
public class JavaApplication287 {
public static class Node{
private Node node;
private Node nextNode;
int data;
Node(int d){
data = d;
nextNode = null;
}
public Node getNode(){return node;}
public void setNode(Node someNode){node = someNode;}
public Node getNextNode(){return nextNode;}
public void setNextNode(Node someNextNode){nextNode = someNextNode;}
public int getData(){return data;}
public void setData(int d){data = d;}
public void printNode(){System.out.println(data);}
}
public static class NodeLinkedList{
private Node head;
private Node tail;
private int size;
NodeLinkedList(Node nodeHead, Node nodeTail, int s){
this.head = nodeHead;
this.tail = nodeTail;
this.size = s;
}
public Node getHead(){return head;}
public void setHead(Node n){head = n;}
public Node getTail(){return tail;}
public void setTail(Node n){tail = n;}
public int getSize(){return size;}
public void setSize(int n){size = n;}
public void printNodeList(){
System.out.println("Head: " + head.getData());
Node current = head;
while (current.nextNode != null){
System.out.println(current.data);
current = current.getNextNode();
}
System.out.println("Tail: " + tail.getData());
}
}
public static void main(String[] args) {
// create Sample Nodes
Node zero = new Node(0);
Node one = new Node(1);
Node two = new Node(2);
Node three = new Node(3);
Node four = new Node(4);
Node five = new Node(5);
//Link Them
zero.setNextNode(one);
one.setNextNode(two);
two.setNextNode(three);
three.setNextNode(four);
four.setNextNode(five);
//Create the Linked Node List with head = one & tail = five
NodeLinkedList myNodeLinkedList = new NodeLinkedList(zero, five, 6);
//Print Current LinkedNodes
myNodeLinkedList.printNodeList();
//Invert the NodeLinkedList
Node position = myNodeLinkedList.getHead(); //Node we look at
Node prev = null; // Store the prev Node
Node node = null; // Temp Node of the next Node in the Linked List
for (int i=0; i< myNodeLinkedList.getSize(); i++){
node = position.getNextNode(); //Store the Next Node so we do not lose access to it
position.setNextNode(prev); // Update current Node's NextNode value
prev = position; // Set previous Node as the Node we are currently looking at
position = node; // Move our position to the next Node
}
//Invert Head and Tail
Node temp = myNodeLinkedList.getHead();
myNodeLinkedList.setHead(myNodeLinkedList.getTail());
myNodeLinkedList.setTail(temp);
//Print Current LinkedNodes
myNodeLinkedList.printNodeList();
}
}
This is working code and here is the output I get,
run:
Head: 0
0
1
2
3
4
Tail: 5
Head: 5
5
4
3
2
1
Tail: 0
BUILD SUCCESSFUL (total time: 0 seconds)
Hope it helps,

Index Out Of Bound Exception Error

I've been working on trying to fix this error for a few hours and i cant figure out where/what is causing the error
(java.lang.IndexOutOfBoundsException: index:68 size: 26)
this creates the alphabet in all caps
String [] myStringsChars= new String[26];
for(int i = 0; i < 26; i++)
{
myStringsChars[i] = new String(Character.toChars(i+65));
System.out.println(myStringsChars[i]);
}
i suspect the cause of the problem is one of these two loops
adds array letters to a linked list and sets it as a node
int j=0;
while (j<myStringsChars.length){
BinaryTree.add(alphabet = new TreeNode(myStringsChars[j]));
if (j<=26){
j++;
}
}
sets the node parents and children
int k =0;
while (k<BinaryTree.size()){
int find=(k-1)/2;
BinaryTree.get(k).setParent(BinaryTree.get(find));
if(k%2 ==0){
(BinaryTree.get(k).getParent()). setRightChild(BinaryTree.get(k));
}
else{
(BinaryTree.get(k).getParent()).setLeftChild(BinaryTree.get(k));
}
k++;
}
here's the rest of my code in case it helps
import java.util.*;
public class TreeExercise
{
public static void main(String args[])
{
String [] myStringsChars= new String[26];
for(int i = 0; i < 26; i++)
{
myStringsChars[i] = new String(Character.toChars(i+65));
System.out.println(myStringsChars[i]);
}
List<TreeNode> BinaryTree = new LinkedList();
int j=0;
while (j<myStringsChars.length){
BinaryTree.add(alphabet = new TreeNode(myStringsChars[j]));
if (j<=26){
j++;
}
}
int k =0;
while (k<BinaryTree.size()){
int find=(k-1)/2;
BinaryTree.get(k).setParent(BinaryTree.get(find));
if(k%2 ==0){
(BinaryTree.get(k).getParent()). setRightChild(BinaryTree.get(k));
}
else{
(BinaryTree.get(k).getParent()).setLeftChild(BinaryTree.get(k));
}
k++;
}
BinaryTree.get(0).setParent(null);
Scanner input= new Scanner(System.in);
String userChoice="";
while (!(userChoice.equals("end"))){
System.out.println("enter two CAPITAL letters to find their common ancestor ex.(DC)\n type 'end' to end program");
userChoice= input.nextLine();
char letter1=userChoice.charAt(0);
char letter2=userChoice.charAt(1);
int let1= (int)letter1;
int let2= (int)letter2;
if(userChoice.length()<=2){
// cant find BinaryTree ERROR
TreeNode commonAncestor= findLowestCommonAncestor(root, BinaryTree.get(let1), BinaryTree.get(let2));
if (commonAncestor !=null){
System.out.println(commonAncestor.getContents());
}
System.out.println("Result is: " + "D");
}
else if (userChoice.equals("end")){
System.exit(0);
}
else{
System.out.println("you must type in 2 capital letters");
userChoice=input.nextLine();
}
}
}
public static TreeNode findLowestCommonAncestor(TreeNode root, TreeNode node1, TreeNode node2)
{
findLowestCommonAncestor(root.getRightChild(), node1, node2)
//every time
TreeNode rightChild= findLowestCommonAncestor(root.getRightChild(), node1, node2);
TreeNode leftChild= findLowestCommonAncestor(root.getLeftChild(), node1, node2);
if (leftChild != null && rightChild!=null){
return root;
}
if(root==null){
return null;
}
if (leftChild!=null){
return leftChild;
}
if(root.getContents()==node1 || root.getContents()==node2){
return root;
}
else {
return rightChild;
}
}
}
TreeNode nodes
public class TreeNode<T extends Comparable>{
private T contents;
private TreeNode<T> parent;
private TreeNode<T> leftChild;
private TreeNode<T> rightChild;
private int level;
public TreeNode()
{
//added
//parent=null;
//leftChild=null;
//rightChild=null;
//level=0;
}
public TreeNode(T data){
contents=data;
this.parent=parent;
}
public TreeNode(T data, TreeNode parent)
{
contents = data;
this.parent = parent;
}
public void setLeftChild(TreeNode node)
{
this.leftChild = node;
}
public void setRightChild(TreeNode node)
{
this.rightChild = node;
}
public boolean isContentEquals(T data)
{
return 0 == getContents().compareTo(data);
}
/**
* #return the contents
*/
public T getContents() {
return contents;
}
/**
* #param contents the contents to set
*/
public void setContents(T contents) {
this.contents = contents;
}
/**
* #return the parent
*/
public TreeNode getParent() {
return parent;
}
/**
* #param parent the parent to set
*/
public void setParent(TreeNode parent) {
this.parent = parent;
}
/**
* #return the leftChild
*/
public TreeNode getLeftChild() {
return leftChild;
}
/**
* #return the rightChild
*/
public TreeNode getRightChild() {
return rightChild;
}
/**
* Given an object T contentToSearch, this method returns
* the node that stores the contentToShare or null if not found on the current tree
* #return the node
*/
public TreeNode findNodeOnTree(T contentToSearch)
{
List<TreeNode> nodes = new LinkedList();
nodes.clear();
nodes.add(this);
while(!nodes.isEmpty())
{
TreeNode current = nodes.remove(0);
if(current.isContentEquals(contentToSearch))
{
return current;
}
if(current.leftChild != null)
{
nodes.add(current.leftChild);
}
if(current.rightChild != null)
{
nodes.add(current.rightChild);
}
}
return null;
}
/**
* #return the level
*/
public int getLevel() {
return level;
}
/**
* #param level the level to set
*/
public void setLevel(int level) {
this.level = level;
}
}
Your error appears to be here, guessing that this is line TreeExercise.java:113:
int let1= (int)letter1;
int let2= (int)letter2;
if(userChoice.length()<=2){
// cant find BinaryTree ERROR
TreeNode commonAncestor= findLowestCommonAncestor(root,
BinaryTree.get(let1), BinaryTree.get(let2));
^^^^ ^^^^
Your tree list is indexed from 0 to 25, but let1 and let2, given an input of DE, are 68 and 69. So, try:
int let1= (int)letter1 - 'A';
int let2= (int)letter2 - 'A';
It would be clearer in your other code, too, to use 'A' rather than 65.

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.

Categories

Resources