How can this class be used and assigned in this manner? - java

I am currently trying to understand Singly linked lists.
I don't understand some of the code in the SinglyLinkedList.java class. How can the Node class be called and then assigned like: private Node first;
I would have thought that you would have to do something like this
Node<T> help =new Node<>();
help = first;
If someone could explain, or provide me to a link that would help me, it would be much appreciated.
Thanks!
public class Node<T> {
public T elem;
public Node<T> next;
public Node(T elem) {
this.elem = elem;
next = null;
}
public Node(T elem, Node<T> next) {
this.elem = elem;
this.next = next;
}
#Override
public String toString() {
return "Node{" + "elem=" + elem + '}';
}
}
package list;
/**
*
* #author dcarr
*/
public class SinglyLinkedList<T> implements List<T> {
private Node<T> first;
private Node<T> last;
public SinglyLinkedList() {
first = null;
last = null;
}
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public int size() {
if (isEmpty()){
return 0;
} else {
int size = 1;
Node<T> current = first;
while(current.next != null){
current = current.next;
size++;
}
return size;
}
}
#Override
public T first() {
return first.elem;
}
#Override
public void insert(T elem) {
// if there is nothing in the list
if (isEmpty()){
first = new Node<>(elem);
last = first;
// if the list has elements already
} else {
// the new element will be the next of what was the last element
last.next = new Node<>(elem);
last = last.next;
}
}
#Override
public void remove(T elem) {
if (!isEmpty()){
int index = 0;
Node<T> current = first;
while (current != null && current.elem != elem){
current= current.next;
index++;
}
remove(index);
}
}
#Override
public String toString() {
if (isEmpty()){
return "Empty List";
} else {
String str = first.elem.toString() + " ";
Node<T> current = first;
while(current.next != null){
current = current.next;
str += current.elem.toString() + " ";
}
return str;
}
}
#Override
public void insertAt(int index, T e) {
if (index == 0){
first = new Node<>(e, first);
if (last == null){
last = first;
}
return;
}
Node<T> pred = first;
for (int i = 0; i < index-1; i++) {
pred = pred.next;
}
pred.next = new Node<>(e, pred.next);
System.out.println(pred);
if (pred.next.next == null){
// what does this mean pred.next is?
last = pred.next;
}
}
#Override
public void remove(int index) {
if (index < 0 || index >= size()){
throw new IndexOutOfBoundsException();
} else if (isEmpty()){
return;
}
if (index == 0){
first = first.next;
if (first == null){
last = null;
}
return;
}
Node<T> pred = first;
for (int i = 1; i <= index-1; i++) {
pred = pred.next;
}
// remove pred.next
pred.next = pred.next.next;
if (pred.next == null){
last = pred;
}
}
}

The first field is automatically initialized to null:
private Node<T> first;
I assume there will be some method to add an element at the end like so:
public void add(T element) {
if (first == null) {
first = new Node<T>(element);
last = first;
}
else {
last.next = new Node<>(element);
last = last.next;
}
}
So when you create a new SinglyLinkedList:
SinglyLinkedList<String> sillyList = new SinglyLinkedList<>();
The first and last fields both hold a null reference.
Note that the first method will cause a NullPointerException at this point. A better implementation would be:
#Override
public Optional<T> first() {
if (first != null) {
return Optional.ofNullable(first.elem);
}
else {
return Optional.empty();
}
}
Now if you add an element:
sillyList.add("Adam");
The code executed in the add method is:
first = new Node<>(elem);
last = first;
So first points to a new Node instance with an elem field holding the value "Adam". And last points to that same Node instance.
Some of the methods in this class I would implement differently, for example:
#Override
public void remove(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative");
}
else if (index == 0 && first != null) {
first = null;
last = null;
}
else {
Node<T> curr = new Node<>("dummy", first);
int c = 0;
while (curr.next != null) {
if (c == index) {
curr.next = curr.next.next;
if (curr.next == null) {
last = curr;
}
return;
}
curr = curr.next;
c++;
}
throw new IndexOutOfBoundsException(String.valueOf(c));
}
Also, some of the methods don't actually exist in the java.util.List interface, like insert, insertAt and first. So these methods must not have the #Override annotation.

Related

How to implement toArray() within a linked list?

I've created a sorted linked list class, and the only part I'm struggling with is implementing the toArray() method properly.
public class SortedLinkedList<T extends Comparable<T>> implements ListInterface<T>
{
// container class
private class LinkedNode<T>
{
public T data;
public LinkedNode<T> next;
public LinkedNode(T data, LinkedNode<T> next)
{
this.data = data;
this.next = next;
}
}
// private variables
private LinkedNode<T> head, tail;
private int size;
private String name;
// constructor
public SortedLinkedList(String name)
{
head = null;
tail = null;
size = 0;
this.name = name;
}
// core functions
public void Add(T data)
{
size++;
// creation of new node to be added
LinkedNode<T> newNode = new LinkedNode<T>(data, null);
// check for empty list; adds node at head if so
if (head == null)
{
head = newNode;
return;
}
if (head.data.compareTo(data) < 0)
{
head = newNode;
return;
}
// insertion in middle
LinkedNode<T> current = head;
LinkedNode<T> prev = null;
while (current != null)
{
if (current.data.compareTo(data) > 0)
{
prev.next = newNode;
newNode.next = current;
return;
}
prev = current;
current = current.next;
}
// insertion at end
prev.next = newNode;
return;
}
public void Remove(T data)
{
if (head == null)
{
return;
}
LinkedNode<T> current = head.next;
while (current != null && current.next != null)
{
if (current.data.compareTo(current.next.data) == 0)
{
current.next = current.next.next;
} else {
current = current.next;
}
}
size--;
}
public int size()
{
return size;
}
#SuppressWarnings("unchecked")
public T[] toArray()
{
T[] result = (T[])(new Comparable[size()]);
int counter = 0;
for ( T item : )
{
result[counter++] = item;
}
return result;
}
The problem I'm having is what I should include after "T item : " in my for/each line. I had no problem with implementing a similar toArray() method in a set class recently, as that was "for each item in the set", but for some reason I'm blanking on what to place there for the linked list.
Try this.
#SuppressWarnings("unchecked")
public T[] toArray()
{
T[] result = (T[])(new Comparable[size()]);
int counter = 0;
for ( LinkedNode<T> cursor = head; cursor != null; cursor = cursor.next )
{
result[counter++] = cursor.data;
}
return result;
}
Actually, the answer to your question is this:
#SuppressWarnings("unchecked")
public T[] toArray() {
T[] result = (T[])(new Comparable[size()]);
int counter = 0;
for (T item : this) {
result[counter++] = item;
}
return result;
}
This is correct, but to do this you have to implement Iterable<T> interface:
public class SortedLinkedList<T extends Comparable<T>> implements ListInterface<T>, Iterable<T> {
#Override
public Iterator<T> iterator() {
return null;
}
// ...
}
Don't use for loop with linked-lists. Try something like below:
LinkedNode cursor = head;
int index = 0;
while (cursor != null ){
result[index] = cursor.data;
cursor = cursor.next;
index++;
}

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: How to implement Dancing Links algorithm (with DoublyLinkedLists)?

I am trying to implement Knuth's Dancing Links algorithm in Java.
According to Knuth, if x is a node, I can totally unlink a node by the following operations in C:
L[R[x]]<-L[x]
R[L[x]]<-R[x]
And revert the unlinking by:
L[R[x]]<-x
R[L[x]]<-x
What am I doing wrongly in my main method?
How do you implement the unlinking and revert in Java?
Here's my main method:
///////////////
DoublyLinkedList newList = new DoublyLinkedList();
for (int i = 0; i < 81; i++) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(i);
newList.addFirst(set);
}
newList.displayList();
// start at 69
newList.getAt(12).displayNode();
//HOW TO IMPLEMENT UNLINK?
//newList.getAt(12).previous() = newList.getAt(12).next().previous().previous();
//newList.getAt(12).next() = newList.getAt(12).previous().next().next();
newList.displayList();
//HOW TO IMPLEMENT REVERT UNLINK?
//newList.getAt(12) = newList.getAt(12).next().previous();
//newList.getAt(12) = newList.getAt(12).previous().next();
System.out.println();
///////////////
Here's the DoublyLinkedList class:
public class DoublyLinkedList<T> {
public Node<T> first = null;
public Node<T> last = null;
static class Node<T> {
private T data;
private Node<T> next;
private Node<T> prev;
public Node(T data) {
this.data = data;
}
public Node<T> get() {
return this;
}
public Node<T> set(Node<T> node) {
return node;
}
public Node<T> next() {
return next;
}
public Node<T> previous() {
return prev;
}
public void displayNode() {
System.out.print(data + " ");
}
#Override
public String toString() {
return data.toString();
}
}
public void addFirst(T data) {
Node<T> newNode = new Node<T>(data);
if (isEmpty()) {
newNode.next = null;
newNode.prev = null;
first = newNode;
last = newNode;
} else {
first.prev = newNode;
newNode.next = first;
newNode.prev = null;
first = newNode;
}
}
public Node<T> getAt(int index) {
Node<T> current = first;
int i = 1;
while (i < index) {
current = current.next;
i++;
}
return current;
}
public boolean isEmpty() {
return (first == null);
}
public void displayList() {
Node<T> current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public void removeFirst() {
if (!isEmpty()) {
Node<T> temp = first;
if (first.next == null) {
first = null;
last = null;
} else {
first = first.next;
first.prev = null;
}
System.out.println(temp.toString() + " is popped from the list");
}
}
public void removeLast() {
Node<T> temp = last;
if (!isEmpty()) {
if (first.next == null) {
first = null;
last = null;
} else {
last = last.prev;
last.next = null;
}
}
System.out.println(temp.toString() + " is popped from the list");
}
}
I am not familiar with Knuth's Dancing Links algorithm, but found this article which made it quiet clear. In particular I found this very helpful:
Knuth takes advantage of a basic principle of doubly-linked lists.
When removing an object from a list, only two operations are needed:
x.getRight().setLeft( x.getLeft() )
x.getLeft().setRight(> x.getRight() )
However, when putting the object back in the list, all
is needed is to do the reverse of the operation.
x.getRight().setLeft( x )
x.getLeft().setRight( x )
All that is
needed to put the object back is the object itself, because the object
still points to elements within the list. Unless x’s pointers are
changed, this operation is very simple.
To implement it I added setters for linking / unlinking. See comments:
import java.util.HashSet;
public class DoublyLinkedList<T> {
public Node<T> first = null;
public Node<T> last = null;
static class Node<T> {
private T data;
private Node<T> next;
private Node<T> prev;
public Node(T data) {
this.data = data;
}
public Node<T> get() {
return this;
}
public Node<T> set(Node<T> node) {
return node;
}
public Node<T> next() {
return next;
}
//add a setter
public void setNext(Node<T> node) {
next = node;
}
public Node<T> previous() {
return prev;
}
//add a setter
public void setPrevious(Node<T> node) {
prev = node;
}
public void displayNode() {
System.out.print(data + " ");
}
#Override
public String toString() {
return data.toString();
}
}
public void addFirst(T data) {
Node<T> newNode = new Node<T>(data);
if (isEmpty()) {
newNode.next = null;
newNode.prev = null;
first = newNode;
last = newNode;
} else {
first.prev = newNode;
newNode.next = first;
newNode.prev = null;
first = newNode;
}
}
public Node<T> getAt(int index) {
Node<T> current = first;
int i = 1;
while (i < index) {
current = current.next;
i++;
}
return current;
}
public boolean isEmpty() {
return (first == null);
}
public void displayList() {
Node<T> current = first;
while (current != null) {
current.displayNode();
current = current.next;
}
System.out.println();
}
public void removeFirst() {
if (!isEmpty()) {
Node<T> temp = first;
if (first.next == null) {
first = null;
last = null;
} else {
first = first.next;
first.prev = null;
}
System.out.println(temp.toString() + " is popped from the list");
}
}
public void removeLast() {
Node<T> temp = last;
if (!isEmpty()) {
if (first.next == null) {
first = null;
last = null;
} else {
last = last.prev;
last.next = null;
}
}
System.out.println(temp.toString() + " is popped from the list");
}
public static void main(String[] args) {
///////////////
DoublyLinkedList newList = new DoublyLinkedList();
for (int i = 0; i < 81; i++) {
HashSet<Integer> set = new HashSet<Integer>();
set.add(i);
newList.addFirst(set);
}
newList.displayList();
// start at 69
Node node = newList.getAt(12);
node.displayNode(); System.out.println();
//HOW TO IMPLEMENT UNLINK?
node.previous().setNext(node.next);
node.next().setPrevious(node.previous());
//The 2 statements above are equivalent to
//Node p = node.previous();
//Node n = node.next();
//p.setNext(n);
//n.setPrevious(p);
newList.displayList();
//HOW TO IMPLEMENT REVERT UNLINK?
node.previous().setNext(node);
node.next().setPrevious(node);
newList.displayList(); System.out.println();
///////////////
}
}

Need help on unchecked operations java

I am learning algorithms myself, and I tried to implement LinkedList in Java with generic types from scratch. I had a version with Object which works well, but when I updated it with generic types, it gives warnings. Can anybody help where does the "unchecked or unsafe operations" come from?
class LinkedListGeneric <T> {
private Node<T> head;
private int size;
public LinkedListGeneric() {
head = null;
size = 0;
}
public int size() {
return size;
}
public void add (T data) {
if (head == null) {
head = new Node<T> (data);
size = 1;
}
else {
Node<T> temp = new Node<T> (data);
search(size).setNext(temp);
size++;
}
}
public void add (T data, int position) {
if (position > size + 1 || position <= 0) {
System.out.println ("error.");
return;
}
Node<T> temp = new Node<T> (data);
if (position == 1) {
temp.setNext(head);
head = temp;
return;
}
Node<T> prev = search(position - 1);
temp.setNext(prev.getNext());
prev.setNext(temp);
}
public void delete (int position) {
if (position > size || position <= 0) {
System.out.println ("error.");
return;
}
if (position == 1) {
size--;
head = head.getNext();
return;
}
Node<T> prev = search(position - 1);
prev.setNext(prev.getNext().getNext());
size--;
}
public T getValue (int position) {
if (position > size || position <= 0) {
System.out.println ("error.");
return null;
}
Node<T> temp = search(position);
return temp.getData();
//return search(position).getData();
}
public int searchData(T data) {
Node<T> temp = head;
int position = 1;
boolean flag = false;
while (temp != null) {
if (temp.getData() == data) {
flag = true;
break;
}
else {
temp = temp.getNext();
position++;
}
}
if (flag) return position;
else return -1;
}
public void print() {
Node<T> temp = head;
int position = 1;
while (temp != null) {
System.out.println("Node " + position + ": " + temp.getData());
temp = temp.getNext();
position++;
}
}
private Node<T> search (int position) {
Node temp = head;
while (position > 0) {
temp = temp.getNext();
}
return temp;
}
private class Node<T> {
private T data;
private Node<T> next;
public Node() {
this.data = null;
next = null;
}
public Node(T data) {
this.data = data;
next = null;
}
public T getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
}
The problem I see is your Node.getNext call is returning a Node instead of a Node<T>. This is equivalent to the method returning Node<Object> instead of the generic type.
So, you should change:
public Node getNext() {
return next;
}
to
public Node<T> getNext() {
return next;
}
Although sbochin's answer will fix some of your warnings, doing the following will fix all of them:
Replace all instances of T within your Node class, including the one in the class declaration, with T2.
Change the return of getNext to Node<T2>
Change the argument type in setNext to Node<T2>.
Change the type of temp in search to Node<T>.
You might also want to add an #SuppressWarnings("unused") to public Node() since that also generates a compiler warning.
You might also want to make your Node class a static class as none of it's methods depend on the LinkedListGeneric<T> object it is in.
Completely alternatively, you could just get rid of the type parameter from Node, which gets rid of all your warnings except the unused warning. You'd have to keep your class nonstatic however.

Class Cast Error trying to use compareTo with node and elements in a linked list

I've looked at a bunch of the questions in this area and can't find one that solves my problem specifically.
Basically, this is a homework assigment where I have a linked list with nodes, which hold an element. The node class (LinearNode) and the element class (Golfer) both implement Comparable and override the compareTo method. However, the runtime fails trying to add a new node to the list (first node is added fine) with a class cast exception: supersenior.LinearNode cannot be cast to supersenior.Golfer. I don't know why it's trying to take the node and compare it to an element of the node to be compared...i've even tried explicitly casting. The following error is observed:
Exception in thread "main" java.lang.ClassCastException: supersenior.LinearNode cannot be cast to supersenior.Golfer
at supersenior.Golfer.compareTo(Golfer.java:12)
at supersenior.LinearNode.compareTo(LinearNode.java:80)
at supersenior.LinearNode.compareTo(LinearNode.java:80)
at supersenior.LinkedList.add(LinkedList.java:254)
at supersenior.SuperSenior.main(SuperSenior.java:100)
Any help would be greatly appreciated. Thanks!
LinkedList class:
package supersenior;
import supersenior.exceptions.*;
import java.util.*;
public class LinkedList<T> implements OrderedListADT<T>, Iterable<T>
{
protected int count;
protected LinearNode<T> head, tail;
/**
* Creates an empty list.
*/
public LinkedList()
{
count = 0;
head = tail = null;
}
public T removeFirst() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
LinearNode<T> result = head;
head = head.getNext();
if (head == null)
tail = null;
count--;
return result.getElement();
}
public T removeLast() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
LinearNode<T> previous = null;
LinearNode<T> current = head;
while (current.getNext() != null)
{
previous = current;
current = current.getNext();
}
LinearNode<T> result = tail;
tail = previous;
if (tail == null)
head = null;
else
tail.setNext(null);
count--;
return result.getElement();
}
public T remove (T targetElement) throws EmptyCollectionException,
ElementNotFoundException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
boolean found = false;
LinearNode<T> previous = null;
LinearNode<T> current = head;
while (current != null && !found)
if (targetElement.equals (current.getElement()))
found = true;
else
{
previous = current;
current = current.getNext();
}
if (!found)
throw new ElementNotFoundException ("List");
if (size() == 1)
head = tail = null;
else if (current.equals (head))
head = current.getNext();
else if (current.equals (tail))
{
tail = previous;
tail.setNext(null);
}
else
previous.setNext(current.getNext());
count--;
return current.getElement();
}
public boolean contains (T targetElement) throws
EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException ("List");
boolean found = false;
Object result;
LinearNode<T> current = head;
while (current != null && !found)
if (targetElement.equals (current.getElement()))
found = true;
else
current = current.getNext();
return found;
}
public boolean isEmpty()
{
return (count == 0);
}
public int size()
{
return count;
}
public String toString()
{
LinearNode<T> current = head;
String result = "";
while (current != null)
{
result = result + (current.getElement()).toString() + "\n";
current = current.getNext();
}
return result;
}
public Iterator<T> iterator()
{
return new LinkedIterator<T>(head, count);
}
public T first()
{
return head.getElement();
}
public T last()
{
return tail.getElement();
}
#Override
public void add (T element)
{
LinearNode<T>node = new LinearNode<T>();
node.setElement(element);
if(isEmpty())
{
head = node;
if(tail == null)
tail = head;
//node.setNext(head);
//head.setPrevious(node);
//head.setElement((T) node);
count++;
}
else
{
for(LinearNode<T> current = head; current.getNext() != null; current = current.getNext())
if(node.compareTo((T) current) >= 0)
{
current.setPrevious(current);
current.setNext(current);
}
else
{
current.setPrevious(node);
}
tail.setNext(node);
}
}
}
LinearNode class:
package supersenior;
public class LinearNode<E> implements Comparable<E>
{
private LinearNode<E> next, previous;
public E element;
public LinearNode()
{
next = null;
element = null;
}
public LinearNode (E elem)
{
next = null;
element = elem;
}
public LinearNode<E> getNext()
{
return next;
}
public void setNext (LinearNode<E> node)
{
next = node;
}
public E getElement()
{
return element;
}
public void setElement (E elem)
{
element = elem;
}
#Override
public int compareTo(E otherElement) {
return ((Comparable<E>) this.element).compareTo(otherElement);
}
public LinearNode<E> getPrevious()
{
return previous;
}
public void setPrevious (LinearNode<E> node)
{
previous = node;
}
}
The element class (Golfer):
package supersenior;
public class Golfer implements Comparable<Golfer>{
Golfer imaGolfer;
String name;
int tourneys;
int winnings;
double avg;
public Golfer(String attr[]){
this.name = attr[0];
this.tourneys = Integer.parseInt(attr[1]);
this.winnings = Integer.parseInt(attr[2]);
this.avg = findAvg(winnings, tourneys);
}
private double findAvg(int winnings, int tourneys){
double a = winnings/tourneys;
return a;
}
#Override
public String toString(){
return "Name: " + name + " Tourneys: " + tourneys + " Winnings: " + winnings + " Average: " + avg;
}
#Override
public int compareTo(Golfer golfer) {
if(this.avg <= golfer.avg)
return 1;
if(this.avg == golfer.avg)
return 0;
else
return -1;
}
}
The problem is that you're mixing what's being compared. You're trying to compare the LinearNode object (which holds an E) to an actual E. LinearNode<E> shouldn't implement Comparable<E>; if anything, it might implement Comparable<LinearNode<E>>, and the type parameter should probably be E extends Comparable<E>.
If you want to order LinearNodes based on the ordering of their underlying elements, you should use something like this:
// in LinearNode
public int compareTo(LinearNode<E> otherNode) {
return this.element.compareTo(otherNode.element);
}
(Note that the Java sorted collections don't require elements to implement Comparable, since you can provide a custom Comparator for any of them, but in the case of this assignment it's probably fine to require that E extends Comparable<E>.)
(Note 2: If you're using Generics, any cast, such as your (Comparable<E>), is a red flag; the purpose of the Generics system is to eliminate the need for most explicit casts.)

Categories

Resources