I am new to java and i have encountered a problem while making a generic class with comparable interface. In the sortedInsert method of LinkedList class it gives error on head.value.compareTo(new_node.value), i am making an object of Linkedlist class in main so , according to my understanding head.value should give me an employee object for which i am calling compareTo . but still it gives me this error . is there anything i understood incorrectly ? or making a mistake in this code .
cannot find symbol
symbol: method compareTo(T)
public class Employee implements Comparable<Employee>
{
private int empID;
private String name;
private int salary;
private boolean manager;
private int subordinates;
public Employee()
{
empID = 0;
name = "";
salary = 0;
manager = false;
subordinates = 0;
}
public Employee(int id , String name , int salary , boolean manager , int sub)
{
empID = id;
this.name = name;
this.salary = salary;
this.manager = manager;
subordinates = sub;
}
public int GetID()
{
return this.empID;
}
public String GetName()
{
return this.name;
}
#Override
public int compareTo(Employee other)
{
if (this.empID < other.empID)
{
return -1;
}
else if (this.empID > other.empID)
{
return 1;
}
else
{
return 0;
}
}
public class LinkedList<T>
{
private int count;
private Node<T> head;
private class Node<T>
{
public T value;
public Node<T> next;
public Node(T data)
{
this.value = data;
this.next = null;
}
}
LinkedList()
{
count = 0;
head = null;
}
void sortedInsert(T data)
{
Node<T> current;
Node<T> new_node = new Node<T>(data);
/* Special case for head node
head.value >= newNode*/
if (head == null || (head.value.compareTo(new_node.value) == 1 || head.value.compareTo(new_node.value) == 0))
{
new_node.next = head;
head = new_node;
}
else {
current = head;
while (current.next != null && (current.next.value.compareTo(new_node.value) == -1))
current = current.next;
new_node.next = current.next;
current.next = new_node;
}
}
You could try to switch to this:
public class LinkedList<T extends Comparable<T>>
The head.value variable is not necessarily something that implements Comparable interface. You need to either define your LinkedList<T> such that it must implement Comparable (see #algrid's answer) or cast it when using the compareTo method.
Related
I am currently writing a program that creates Students and stores them in a doubly linked list based on their natural order (Last name, First name, GPA, then student ID). I am just starting off with generics and how they work so I am a little lost. I believe most of my code is working; the only part I need help with is adding students (who have multiple data types) into my list in my main method in my doubly linked list class. Any help is greatly appreciated! Here is my student, doubly linked list, and node class along with a fragment of the input file I am reading from with the data of each student:
Student class:
public class Student{
long studentID;
String firstName;
String lastName;
float GPA;
public Student(String lastName, String firstName, float GPA, long studentID){
this.lastName = lastName;
this.firstName = firstName;
this.GPA = GPA;
this.studentID = studentID;
}
public int compareTo(Student s){
int result = this.lastName.compareTo(s.lastName);
if(result == 0){
result = this.firstName.compareTo(s.firstName);
if(result == 0){
result = Float.compare(this.GPA, s.GPA);
if(result == 0){
result = Long.compare(this.studentID, s.studentID);
}
}
}
return result;
}
public String toString(){
return this.lastName + ", " + this.firstName +
" GPA: " + this.GPA + " ID: " + this.studentID;
}
}
Node class:
public class Node<T>{
Node<T> previous;
Node<T> next;
Student data;
public Node(Student data){
this(data, null, null);
}
public Node(Student data, Node<T> previous, Node<T> next){
this.data = data;
this.previous = previous;
this.next = next;
}
}
Doubly Linked List class:
import java.io.*;
import java.util.*;
import csci1140.*;
public class DoublyLinkedList<T> implements Iterable<Node>{
private Node root;
private Node tail;
private Node previous;
private class ListIterator implements Iterator<Node>{
Node current = root;
public boolean hasNext(){
return (current != null);
}
public Node next(){
Node answer;
answer = current;
current = current.next;
return answer;
}
}
public Iterator<Node> iterator(){
ListIterator listIterator = new ListIterator();
return listIterator;
}
public void add(T data){
Node<Student> newNode = new Node<Student>(data);
if(root == null){
root = newNode;
tail = root;
return;
}
Node current = root;
for( ; current!= null; current = current.next){
if(newNode.data.compareTo(current.data)<= 0){
break;
}
}
if(previous == null){
previous.next = newNode;
newNode.next = current;
if(current == null){
tail = newNode;
}
} else {
newNode.next = root;
root = newNode;
}
}
public static final void main(String[] args){
FileInputStream fileIn = null;
try{
fileIn = new FileInputStream("student_input.txt");
System.setIn(fileIn);
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace(System.err);
}
//Do work here to create list of students
}
try{
fileIn.close();
} catch(Exception e){}
}
}
Student_input.txt:
1000
Lisa
Licata
2.28
1001
Shelley
Santoro
1.56
1002
Ok
Ota
3.33
1003
Cindi
Caggiano
1.65
Still not completely sure, maybe some variation of this.
Especially this inserts before the first Node that is bigger, and I am still not sure what the generics are for in this case and T needs to be something that extends Student(well it needs the compareTo method):
public void add(T data) {
for(Node<T> current = root; current != null; current = current.next) {
if (data.compareTo(current.data) <= 0) {
current = new Node<>(data,current.previous,current);
if(null == current.previous){
root = current;
}else {
current.previous.next = current;
}
if(null == current.next){
tail = current;
} else {
current.next.previous = current;
}
return;
}
}
tail = new Node<>(data,tail,null);
if(null == tail.previous) root=tail;
}
So your list should maybe look like this(to ensure T has the compareTo method):
public class DoublyLinkedList<T extends Student> implements Iterable<Node<T>> {
...
}
All together(To have Node as a seperate file like you do is better - but for brevity I put it into the list):
public class DoublyLinkedList<T extends Student> implements Iterable<Node<T>> {
public static class Node<S> {
Node<S> previous;
Node<S> next;
S data;
public Node(S data) {
this(data, null, null);
}
public Node(S data, Node<S> previous, Node<S> next) {
this.data = data;
this.previous = previous;
this.next = next;
}
}
private Node<T> root = null;
private Node<T> tail = null;
private class ListIterator implements Iterator<Node<T>> {
Node<T> current = root;
#Override
public boolean hasNext() {
return (current != null);
}
#Override
public Node<T> next() {
Node<T> answer;
answer = current;
current = current.next;
return answer;
}
}
#Override
public Iterator<Node<T>> iterator() {
ListIterator listIterator = new ListIterator();
return listIterator;
}
public void add(T data) {
for(Node<T> current = root; current != null; current = current.next) {
if (data.compareTo(current.data) <= 0) {
current = new Node<>(data,current.previous,current);
if(null == current.previous){
root = current;
}else {
current.previous.next = current;
}
if(null == current.next){
tail = current;
} else {
current.next.previous = current;
}
return;
}
}
tail = new Node<>(data,tail,null);
if(null == tail.previous) root=tail;
}
}
I am working on a custom Linked List based on Crunchify's implementation to display list of Employee. As of now I can add new Employee or remove existing Employee from the list. However, my project requires adding a sorting method that would not be based on Collections.sort(). My teacher wants this sorting method to be custom, so this is quite difficult for me. Is there anyway to sort this list by first name that is easy to code (I'm completely new to object oriented programming)?
Here is my custom Linked List:
import java.util.Scanner;
import java.io.IOException;
public class MyLinkedListTest2 {
public static MyLinkedList linkededList;
public static void main(String[] args) {
linkededList = new MyLinkedList();
linkededList.add(new Employee("Agness", "Bed", 2000.0, 32));
linkededList.add(new Employee("Adriano", "Phuks", 4000.0, 16));
linkededList.add(new Employee("Panda", "Mocs", 6000.0, 35));
System.out.println(linkededList);
//OPTIONS
Scanner scanner = new Scanner(System.in);
int selection;
do {
System.out.println("OPTIONS:\n[1] ADD EMPLOYEE\n[2] REMOVE EMPLOYEE\n[3] SORT \n[4] EXIT\n");
selection = scanner.nextInt();
switch (selection) {
case 1:
System.out.println("Name:");
scanner.nextLine();
String name = scanner.nextLine();
System.out.println("Surname:");
String surname = scanner.nextLine();
System.out.println("Salary:");
double salary = scanner.nextDouble();
System.out.println("Experience:");
int experience = scanner.nextInt();
linkededList.add(new Employee(name, surname, salary, experience));
System.out.println(linkededList);
break;
case 2:
System.out.println("Which row do you want to remove?");
int choice = scanner.nextInt();
if (choice == 0)
System.out.println("No such row exists");
else if (choice > linkededList.size())
System.out.println("No such row exists");
else
linkededList.remove(choice - 1);
System.out.println(linkededList);
break;
case 3:
System.out.println("SORT BY: 1.NAME\t2.SURNAME\t3.SALARY\t4.EXPERIENCE\n");
//In this section sorting algorithm should be added
break;
case 4:
break;
default:
System.out.println("Wrong choice");
}
} while (selection != 4);
}
}
class MyLinkedList<Employee> {
private static int counter;
private Node head;
public MyLinkedList() {
}
public void add(Object data) {
if (head == null) {
head = new Node(data);
}
Node myTemp = new Node(data);
Node myCurrent = head;
if (myCurrent != null) {
while (myCurrent.getNext() != null) {
myCurrent = myCurrent.getNext();
}
myCurrent.setNext(myTemp);
}
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
public void add(Object data, int index) {
Node myTemp = new Node(data);
Node myCurrent = head;
if (myCurrent != null) {
for (int i = 0; i < index && myCurrent.getNext() != null; i++) {
myCurrent = myCurrent.getNext();
}
}
myTemp.setNext(myCurrent.getNext());
myCurrent.setNext(myTemp);
incrementCounter();
}
public Object get(int index){
if (index < 0)
return null;
Node myCurrent = null;
if (head != null) {
myCurrent = head.getNext();
for (int i = 0; i < index; i++) {
if (myCurrent.getNext() == null)
return null;
myCurrent = myCurrent.getNext();
}
return myCurrent.getData();
}
return myCurrent;
}
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node myCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (myCurrent.getNext() == null)
return false;
myCurrent = myCurrent.getNext();
}
myCurrent.setNext(myCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node myCurrent = head.getNext();
while (myCurrent != null) {
output += myCurrent.getData().toString();
myCurrent = myCurrent.getNext();
}
}
return output;
}
public void compare(int index){
Node myCurrent = head.getNext();
if(myCurrent != myCurrent.getNext())
myCurrent = head;
else
myCurrent = myCurrent.getNext();
}
private class Node {
Node next;
Object data;
public Node(Object dataValue) {
next = null;
data = dataValue;
}
#SuppressWarnings("unused")
public Node(Object dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
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;
}
}
}
Also, here is my Employee class that the list is based on:
public class Employee
{
private String firstName;
private String lastName;
private double salary;
private int experience;
public Employee(String firstName, String lastName, double salary, int experience)
{
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
this.experience = experience;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public double getSalary()
{
return salary;
}
public int getExperience()
{
return experience;
}
#Override
public String toString()
{
String ret = "\n" +"Name: "+firstName +" | Surname: "+lastName +" | Salary: "+salary + " | Experience: "+experience +"\n";
return ret;
}
}
The code is compiling now, but maybe you have some recommendation regarding this implementation of Linked List? I would be grateful if someone comes up with a solution for sorting, since with this my project will be completed. Only Comparable can be used, while Collections.sort() method cannot be implemented due to project's requirements.
You can define your own EmployeeComparator that implements Comparator<Employee> (see comparator) and use it like following :
SortedSet<Employee> set = new TreeSet<Employee>(new EmployeeComparator());
set.addAll(employees);
Since you need to implement the sorting yourself, one of the easiest way could be so compare each list node with the next one and swap them if they are not in sorted order. You need to do this until there is any such out of order nodes left in the list.
You can see bubble sort implementation for an idea on how this works.
Node
private Object data;
private Node link;
private Node next;
private Node prev;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
public Node(Object data) {
this.data = data;
this.link = null;
}
public Node getNextNode() {
return next;
}
public Node getPrevNode() {
return prev;
}
public void setNextNode(Node n) {
next = n;
}
public void setPrevNode(Node n) {
prev = n;
}
Item
private int id;
private String name;
private String type;
private double price;
public Item(int id, String name, String type, double price) {
this.id = id;
this.name = name;
this.type = type;
this.price = price;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public double getPrice() {
return price;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Item: " + "ID: " + id + ", Name: " + name + ", Type: " + type + ", Price: " + price;
}
LinkedList
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
newNode.setLink(head);
head = newNode;
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getLink();
count--;
}
}
public void AddItemToFront(Item p) {
Node newNode = new Node(p);
newNode.setLink(head);
head = newNode;
count++;
}
public void DisplayItems() {
Node temp = head;
while(temp != null) {
System.out.println(temp.getData());
temp = temp.getLink();
}
}
public void RemoveItemAtPosition(int n) {
if(n == 1) {
Node x = head;
head = x.getLink();
count--;
}
else if (n > count || n < 0) {
System.out.println("The index you entered is out of bound.");
}
else {
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Node temp = x;
x = temp.getPrevNode();
x.setNextNode(temp.getNextNode());
temp = null;
count--;
}
}
I'm trying to remove a Node at a position given integer n.
I tried researching on SO before posting here and the above is the code that i came out with. However, the code returned me an error saying >java.lang.NullPointerException at LinkedList.java:74 at main:35
The Node is actually an object that is being added to the LinkedList
I checked your code I see that you have some bugs.
your mistakes are:
1 -you use linked object.
2- try to access previous and next without initialization.
3- you only care on the next node.
I removed link form Node class and I do some changes into LinkedList:
public class LinkedList {
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
if (head == null) {
head = newNode;
} else {
Node node = head;
head = newNode;
head.setNextNode(node);
node.setPrevNode(head);
}
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getNextNode();
head.setPrevNode(null);
count--;
}
}
public void AddItemToFront(Item p) {
Node newNode = new Node(p);
if (head == null) {
head = newNode;
} else {
Node node = head;
head = newNode;
head.setNextNode(node);
node.setPrevNode(head);
}
count++;
}
public void DisplayItems() {
Node temp = head;
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNextNode();
}
}
public void RemoveItemAtPosition(int n) {
if (n == 1) {
deleteFront();
} else if (n > count || n < 0) {
System.out.println("The index you entered is out of bound.");
} else {
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Node temp = x;
temp.getPrevNode().setNextNode(temp.getNextNode());
temp.getNextNode().setPrevNode(temp.getPrevNode());
temp = null;
count--;
}
}
}
When checking the provided source code, in the function AddItemToFront(Item p) only the linked-list is managed with newNode.setLink(head);. Both Node next; and Node prev; are never initialized and never used before in the function removeItemAtPosition(int n).
Warning: your Linked-List is managed on reverse (due to the function void AddItemToFront(Item p)).
A simple way to solve your problem should to use only Node link; also in the function removeItemAtPosition(int n).
Step 1 - in RemoveItemAtPosition(int n), modify the search of the nth Node in the for-loop
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getLink(); // Use Node link
}
Instead of
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Step 2 - in RemoveItemAtPosition(int n), connect the next node link to the node before
Node temp = x.getLink();
x.setLink(temp.getLink());
count--;
Instead of
Node temp = x;
x = temp.getPrevNode();
x.setNextNode(temp.getNextNode());
temp = null;
count--;
I implemented a priority queue with linked list like this,when for first time I make an object from seller class and add it to priority queue, it works, but when I make second object from seller to
add it to priority queue,it gives an error, I know that my comparator makes this error, but I don't
know, how can I compare objects, please help me!
import java.util.Comparator;
public class PQueueTest {
public static void main(String [] args) {
DefaultComparator<Seller> o = new DefaultComparator<>();
Seller s = new Seller("ali", 125, 200);
Seller s1 = new Seller("hasan", 50, 100);
PriorityQueue<Seller> p = new PriorityQueue<>(o);
p.add(s);
p.add(s1);
System.out.println(p.removeMin());
System.out.println(p.removeMin());
}
}
class Node<E> {
private E element;
private Node<E> next;
public Node(E element, Node<E> next) {
this.element = element;
this.next = next;
}
public void setNext(Node<E> next) {
this.next = next;
}
public void setElement(E element) {
this.element = element;
}
public Node<E> getNext() {
return next;
}
public E getElement() {
return element;
}
}
class DefaultComparator<E> implements Comparator<E> {
#Override
public int compare(E a, E b) {
return ((Comparable<E>) a).compareTo(b);
}
}
class PriorityQueue<E> {
private int size;
private Node<E> front;
private DefaultComparator<E> c;
public PriorityQueue(Comparator<? super E> o) {
size = 0;
front = null;
c = (DefaultComparator<E>) o;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void add(E element) {
Node<E> v = new Node<>(element, null);
if (isEmpty()) {
front = v;
}
if (size >= 1) {
Node<E> temp = front;
int comp = c.compare(element, temp.getElement());
while (comp >= 0 && temp.getNext() != null) {
temp = temp.getNext();
comp = c.compare(element, temp.getElement());
}
if (comp < 0) {
// E x = temp.getElement();
v.setNext(temp);
if (temp == front)
front = v;
else {
Node<E> tmp = front;
while (tmp.getNext() != temp) {
tmp = tmp.getNext();
}
tmp.setNext(v);
}
}
if (comp >= 0)
temp.setNext(v);
}
size++;
}
public E removeMin() {
E remove = front.getElement();
front = front.getNext();
size--;
return remove;
}
public E removeMax() {
Node<E> tmp = front;
while (tmp.getNext().getNext() != null) {
tmp = tmp.getNext();
}
E remove = tmp.getNext().getElement();
tmp.setNext(null);
size--;
return remove;
}
public E peekMin() {
E remove = front.getElement();
return remove;
}
public E peekMax() {
Node<E> tmp = front;
while (tmp.getNext().getNext() != null) {
tmp = tmp.getNext();
}
E remove = tmp.getNext().getElement();
return remove;
}
}
class Seller {
private String name;
private long price;
private int stock;
public Seller(String name, long price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(long price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getName() {
return name;
}
public long getPrice() {
return price;
}
public int getStock() {
return stock;
}
}
class Buyer {
private String name;
private long price;
private int stock;
public Buyer(String name, long price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(long price) {
this.price = price;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getName() {
return name;
}
public long getPrice() {
return price;
}
public int getStock() {
return stock;
}
}
First of all: The error is that the cast to Comparable fails. I.e., this line of code:
return ((Comparable<E>)a).compareTo(b);
The reason for that is, that a (in your case, an instance of Seller) does not implement the Comparable interface. You want to compare instances of Seller, so Seller needs to implement the interface (and the corresponding methods):
class Seller implements Comparable<Seller> {
However you should be aware that Comparator and Comparable are usually two opposing concepts. While the implementation of Comparable allows instances of a class to compare themselves with other instances of that class, with a Comparator this comparison is encapsuled inside another class. Combining those concept usually makes no sense.
So you should
Understand what, why and how you should compare
Decide on one of the two concepts (Comparable or Comparator). Googling this should bring up good results.
If it's the Comparator, assert that only those types can be passed to your Comparator that can be handled by it (hint: take a look at the generic parameter)
And last but not least: Take a look at the warnings your IDE gives you about type safety. Understand them and you will find the major flaw in your code.
I created my own linkedlist. I wanted to sort my linkedlist using Collections.sort method.
So I extends MyLinkedList class to java.util.LinkedList. I also created Comparator and Comparable implementation. But both are not working. Please find below code.
// Linked List implementation.
package com.java.dsa;
class Node<E> {
E data;
Node<E> nextLink;
public Node(E data) {
this.data = data;
}
}
public class MyLinkedList<E> extends java.util.LinkedList<E>{
private static final long serialVersionUID = 1L;
private Node<E> firstNodePointer;
private Node<E> nodePointer;
public boolean isEmpty() {
return nodePointer == null;
}
public boolean add(E data) {
super.add(data);
Node<E> node = new Node<E>(data);
if (firstNodePointer == null) {
firstNodePointer = node;
nodePointer = node;
}else{
nodePointer.nextLink = node;
}
nodePointer = node;
return true;
}
public boolean remove(Object data){
super.remove(data);
Node<E> counterNodePointer = firstNodePointer;
Node<E> tempNodePointer = firstNodePointer;
while (counterNodePointer != null && !counterNodePointer.data.equals(data)) {
tempNodePointer = counterNodePointer;
counterNodePointer = counterNodePointer.nextLink;
}
if(tempNodePointer.equals(firstNodePointer)){
firstNodePointer = firstNodePointer.nextLink;
return true;
}
else if(counterNodePointer != null && tempNodePointer != null){
tempNodePointer.nextLink = counterNodePointer.nextLink;
return true;
}
return false;
}
public void printList() {
Node<E> counterNodePointer = firstNodePointer;
while (counterNodePointer != null) {
System.out.println(counterNodePointer.data);
counterNodePointer = counterNodePointer.nextLink;
}
}
}
// Test Linkedlist
package com.java.dsa;
import java.util.Collections;
import java.util.Comparator;
//Employee Class
class Employee implements Comparable<Employee> {
private String name;
private int id;
public Employee(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
#Override
public String toString() {
return this.name + " " + this.id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public int compareTo(Employee employee) {
return this.id - employee.id;
}
}
class EmployeeSort implements Comparator<Employee> {
#Override
public int compare(Employee emp1, Employee emp2) {
if (emp2.getId() - emp1.getId() > 0)
return 1;
else
return -1;
}
}
public class TestLinkedList {
public static void main(String[] args) {
MyLinkedList<Employee> myList = new MyLinkedList<Employee>();
for (int i = 10; i > 0; i--) {
Employee emp = new Employee("Sohan "+i, i);
myList.add(emp);
}
myList.printList();
Collections.sort(myList, new EmployeeSort());
myList.printList();
}
}
Actually it works. It's just that your internal data structure is not updated by Collections.sort(), and since you base your assertion that the program doesn't work on the output of printList(), and this relies on that data structure, you see the order of elements untouched. Use this method instead:
public void printParentDataStructure() {
for ( E e : this ) System.out.println( e );
}
and see that your comparator perfectly does its job. So your problem is that you have two data structures and don't keep them in sync. Your next question may be "And how can I keep them sync'ed?" - Well, essentially you should override each and every method, and call super() like you do in add() and remove(). Don't do that! It'd be a complete nonsense.
It's clear that you want to implement a linked list for learning the data strcuture, but maybe you should first better understand the basic principles of OOP programming.
java.util.LinkedList is not a class designed for subclassing and your code is probably just breaking its internals and invariants.
If you want to implement a linked list on your own, but want to save yourself the effort of implementing the full List interface, then use AbstractList as your base class. This class's express purpose is exactly what you are trying to do.