java sorted node list example - java

I am new to node lists and I need to search check whether a PersonNode associated with the given ID is in the list
the is my PersonNode class
public class PersonNode
{
// instance variables
private int m_ID;
private String m_name;
private PersonNode m_link;
// constructor
public PersonNode(int ID, String name)
{
m_ID = ID;
m_name = name;
m_link = null;
}
// getters and setters
public void setID(int ID)
{
m_ID = ID;
}
public int getID()
{
return m_ID;
}
public String getName()
{
return m_name;
}
public void setName(String name)
{
m_name = name;
}
public void setLink(PersonNode link)
{
m_link = link;
}
public PersonNode getLink()
{
return m_link;
}
}
here is my method class, constructor and instance variable. The method I don't know how to do is the contains method.
I edited this Class and I am still having so much trouble with this any help would be greatly appreciated.
public class SortedPersonList
{ // instance variables
private PersonNode m_first;
private int m_numElements;
// constructor
// Do not make any changes to this method!
public SortedPersonList()
{
m_first = null;
m_numElements = 0;
}
// check whether the list is empty
// Do not make any changes to this method!
boolean isEmpty()
{
if (m_first == null)
return true;
else
return false;
}
// return the size of the list (# of Person nodes)
// Do not make any changes to this method!
public int size()
{
return m_numElements;
}
// check whether a PersonNode associated with the given ID is in the list
public boolean contains(int ID)
{This Method I need help with!!
}
// search for and return the PersonNode associated with the given ID
public PersonNode get(int ID)
{ PersonNode current=m_first;
while(current!=null)
{if (current.getID()==ID)
return current;
}
return null;
}
// add a new PersonNode to the list with the given ID and name
public boolean add(int ID, String name)
{ PersonNode newNode=new PersonNode(ID,name);
PersonNode previous=null;
if (m_first == null)
{ // add element to an empty list
m_first = newNode;
m_first.setLink(previous);
m_numElements++;}
else
{if (newNode.getID()<m_first.getID())
{previous=m_first;
m_first=newNode;
m_first.setLink(previous);
m_numElements++;
}
else
{ m_first.setLink(newNode);
newNode.setLink(previous);
m_numElements++;}}
return true; // replace this statement with your own return
}
// remove a PersonNode associated with the given ID from the list
public boolean remove(int ID)
{PersonNode remove = get(ID);
while(remove.getID()==ID)
{m_first=null;
m_first.setLink(remove.getLink());}
m_numElements --;
return true;}
public String toString()
{
String listContent = "";
PersonNode current = m_first;
while (current != null)
{
listContent += "[" + current.getID() + " | " + current.getName() + "] ";
current = current.getLink();
}
return listContent;
}
}
If it helps the goal is to fix the add, contains, remove and get methods to implement a sorted linked list.

Let's assume you have a List<PersonNode> lst. You want to check if a PersonNode with id = ID is in this list lst. You can do that rather easily by just iterating over the list:
public boolean contains(int ID) {
for (PersonNode node : lst) {
if (node.getID() == ID)
return true; // node found, we can finish iterating
}
return false; // no node with id = ID was found
}
Take note that as of this moment you don't have a list in your SortedPersonList class. You probably want to have one as an instance variable.
Alternatively, if you decide that what you wanted to implement is an equivalent of a LinkedList, then you can do the same iteration just without foreach and instead advance with node.getNext()...

Related

Binary Search Tree find method returning not found

This is a homework assignment i'm working on and I'm having a little trouble with it. I've implemented my own version of a binary search tree rather than using JDK. I'm inserting multiple student objects into the binary search tree in terms of the student's ID, which is a type string. I'm not getting any compile errors but the program keeps returning that the value is not found when it should be the fourth student that was inserted into the tree. I've implemented all of the find methods already, but not sure where I'm going wrong with them, since the output should be saying that the value was found.
Output:
run:
11114 not found
BUILD SUCCESSFUL (total time: 0 seconds)
Homework5.class / main:
package homework5;
import java.util.LinkedList;
public class Homework5 {
static Roster rost = new Roster();
public static void main(String[] args) {
addStudent();
lookupStudent("11114");
}
// add students to the roster
static void addStudent() {
rost.addStudent(new Student("11111", "Jon", "Benson"));
rost.addStudent(new Student("11112", "Erick", "Hooper"));
rost.addStudent(new Student("11113", "Sam", "Shultz"));
rost.addStudent(new Student("11114", "Trent", "Black"));
rost.addStudent(new Student("11115", "Michell", "Waters"));
rost.addStudent(new Student("11116", "Kevin", "Johnson"));
}
// lookup a student in the roster
static void lookupStudent(String id) {
if (rost.find(id) != null) {
System.out.println(id + " found");
} else {
System.out.println(id + " not found");
}
}
}
Student.class
class Student implements Comparable<Student> {
String id;
String firstName;
String lastName;
Student(String id, String fName, String lName) {
this.id = id;
this.firstName = fName;
this.lastName = lName;
}
public String getName() {
return lastName;
}
public void setName(String lName) {
this.lastName = lName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int compareTo(Student other) {
return this.getId().compareTo(other.getId());
}
public void addCourse(String id) {
LinkedList list = new LinkedList();
list.add(id);
}
}
Roster.class
class Roster {
Student root;
int numStudents;
BST<Student> roster = new BST<>();
public Roster() {
root = null;
numStudents = 0;
}
public void addStudent(Student st) {
roster.insert(st);
numStudents++;
}
public Student find(String id) {
roster.find(id);
return null;
}
BST.java
package homework5;
class BST<Roster extends Comparable> {
private Node root;
public BST() {
root = null;
}
// Generic find method
public Node find(String id) {
Node current = root;
while (id.compareTo(current.element.getId()) != 0) {
if (id.compareTo(current.element.getId()) < 0) {
current = current.left;
}
else {
current = current.right;
}
if (current == null) {
return null;
}
}
return current;
}
public void insert(Student st) {
Node newNode = new Node(st);
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (st.compareTo(current.element) < 0) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
// Recursive method - traverse generic BST
// While root is not equal to null visit left node and print value
// of root, then visit right node. Repeat until root becomes null
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.element + " ");
inOrder(localRoot.right);
}
}
}
class Node {
protected Student element;
protected Node left;
protected Node right;
public Node(Student st) {
element = st;
}
}
Roster.find() always returns null.
Change it to
public Student find(String id) {
return roster.find(id).element;
}
your code looks fine... a few misconceptions like the comments suggested, just change those couple of lines
public Student find(String id) {
return roster.find(id);
}
and return current.element from roster.find() change the signature to public Student find(String id)
Note: keep in mind this will effect the generic property of the code, a better approach is to implement node as a generic data container e.g Node<Student> make roster.find() return a Node object and get the data from the node so you can return Student object at the end
or at least change only this function instead (it's a better solution than mine)
public Student find(String id) {
return roster.find(id).element;
}

Check duplicate object id in arraylist

I have a list of an Object and I want to detect whether Object Id is duplicate or not.
Here is the object:
public class data{
private String id;
private String value;
private String status;
}
All duplicate data will have "invalid" status except the first one.
What is the most effective way for this?
You could consider overriding the .equals() method of the data class.
Doing so would allow you to do the following to check for duplicate elements:
ArrayList<data> array_list = new ArrayList<data>();
// add some elements to array list
// check for duplicates
for(int i =0; i < array_list.size(); i++){
for(int j=0; j<array_list.size(); j++){
// compare for equality if it is not the same element
if(i != j){
if(array_list.get(i).equals(arrayList.get(j))){
// than we know there is a duplicate at index i,j
System.out.println("duplicate indexes: " + i + ", " + "j");
}
}
}
}
Here is an example of how you would override the .equals method of the data class.
#Override
public boolean equals(Object obj) {
if (!(obj instanceof data)){ return false; }
if (obj == this) { return true; }
// compare strings to see if they are equal
data other_data = (data)obj;
boolean id_equal = other_data.id.equals(this.id);
boolean value_equal = other_data.value.equals(this.value);
boolean status_equal = other_data.status.equals(this.status);
return id_equal && value_equal && status_equal
}
Edit
If you only want to know whether the id's are equal or not you don't need to override .equals() of the data class.
In this case you need only need to use the first loop and compare the id stings instead of the data objects.
So instead of array_list.get(i).equals(arrayList.get(j),
you would do (assuming you have getter methods for the private members of data):
array_list.get(i).get(id).equals(array_list.get(j).get(id));
Alternatively you could use a method similar to the first one and override .equals() to only compare the id strings.
use java ConcurrentHashMap instead of arraylist.
ConcurrentHashMap<yourid, YourBean> chp = new ConcurrentHashMap<>();
chp.putIfAbsent(yourid, YourBean);
and to list all your id do something like this
for (Entry<yourid, YourBean> e : chp.entrySet())
{
YourBean object = (YourBean )chp.get(e.getKey());
//do what u want with your object, guess that helps
}
Try like this first you should override equals method to check duplicates
private class data{
private String id;
private String value;
private String status;
public data(String id, String value, String status) {
this.id = id;
this.value = value;
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "data{" +
"id='" + id + '\'' +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof data)) return false;
data data = (data) o;
return !(id != null ? !id.equals(data.id) : data.id != null);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
Then test like this
public class Test {
public static void main(String[] args ) {
List<data> dataList=new ArrayList<>();
dataList.add(new data("1","somevalue","somestatus"));
dataList.add(new data("1","somevalue","somestatus"));
dataList.add(new data("1","somevalue","somestatus"));
dataList.add(new data("2","somevalue","somestatus"));
dataList.add(new data("3","somevalue","somestatus"));
List<data>validList=new ArrayList<>();
List<data>duplicateList=new ArrayList<>();
for (data data:dataList){
if (!(validList.contains(data))){
validList.add(data);
System.out.println(validList);
}else{
duplicateList.add(data);
System.out.println(duplicateList);
}
}
}
Make a list of the id of objects. Loop over the list of objects. See if the id of each object is already in the list. If the id is already present, then change the status of the object. Otherwise, add the id of the object to the list.

How to iterate through a list of objects and assign children?

I have a Location POJO that stores Location objects parsed in from a JSON file, which I want to map to a graph. Each node's location in the graph corresponds to it's id field, where id="1" is the start node and id="10" is the goal node.
To solve this I adapted a Node class to include methods such as setWeight(), addChildLocation() etc , But I'm not sure how to create the graph from my list of locations. I know how to create the graph by hard coding the location's and calling addChildren, by doing the following, but not sure how to create it from a list of already available Location objects:
Node LocationOne= new Node("LocationOne", 170);
LocationOne.addChildNode(LocationTwo, 105);
My thoughts on this problem, are that a for..each loop should be used to loop through the locations in the list, and add each location as a child of the previous.
Basically, I'm wondering how the list of Location object's can be iterated through, and addChild be called on each sequential location?
Below is the Location class I'm using to map the Location's to object representations:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
private Map<Location, Integer> children = new HashMap<Location, Integer>();
public Location() {
super();
}
public Location(String name){
this.name = name;
}
public Location(String name, int goalDistance){
this.name = name;
this.approximateDistanceFromGoal = goalDistance;
}
public Location[] children(){
return (Location[]) children.keySet().toArray(new Location[children.size()]);
}
public int getDistance(Location loc){
if(children.get(loc) == null) System.out.println(this.name + ": " + loc.getName());
return children.get(loc);
}
public int getChildLocationCount(){
return children.size();
}
public void addChildLocation(Location child, int distance){
children.put(child, distance);
}
public boolean isLeaf(){
if (children.size() > 0){
return false;
}else{
return true;
}
}
public void removeChild(Location child){
children.remove(child);
}
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isGoalLocation() {
return goalLocation;
}
public void setGoalLocation(boolean goalLocation) {
this.goalLocation = goalLocation;
}
public int getApproximateDistanceFromGoal() {
return approximateDistanceFromGoal;
}
public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
this.approximateDistanceFromGoal = approximateDistanceFromGoal;
}
public Location getParent() {
return parent;
}
public void setParent(Location parent) {
this.parent = parent;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}
If you want to build a graph of any kind, then recognize That a graph is composed of on 2 basic elements:
E -> edge
V -> Vertex (A.K.A node)
Key properties:
Vertices can have any number of edges.
Edges only go between single
nodes (in my implementation I modified this for book keeping sake).
Practically speaking, how you access these will depend on a trade off between functionality and performance. In addition, graph nodes are worthless if they don't contain some of your information. So, we add
Map<String,Object> properties
So we can store some data like:
new Vertext().set("age",10);
We also use named edges so you can do things like:
Graph g = new Graph();
g.addVertex("Doctor",new DrVertex("Dr. Smith"));
g.addVertex("Doctor",new DrVertex("Dr. Cooper"));
List<Vertex> doctors = g.get("Doctor");
assertTrue("Dr. Smith",doctors.get(0));
assertTrue("Dr. Cooper",doctors.get(1));
I have put together the basic structure for how I would implement a generic graph. But some have pointed out that there are graph DB's out there like Neo which are very sophisticated.
Below is the code. Use it if you'd like to model your locations.
/**
* #author Christian Bongiorno
*/
public class Graph {
private class Vertex {
Map<String,Object> properties;
private Map<String,Edge> edges;
public Graph addVertex(String edgeName, Vertex v) {
Edge e = edges.get(edgeName);
if(e == null) {
e = new Edge(this);
edges.put(edgeName,e);
}
e.addVertex(v);
return Graph.this;
}
public Graph addVertex(Vertex v) {
return addVertex("anonymous",v);
}
}
private static class Edge {
Map<String,Object> properties;
Vertex in;
Collection<Vertex> out;
private Edge(Vertex in) {
this.in = in;
}
private void addVertex(Vertex v) {
out.add(v);
}
}
}
You might consider moving this question to codereview.stackexchange.com
Edited
Imagine you code like this:
Location -> Vertex
Location[] -> All connected Locations (Vertices) where i in location[i] is the Edge
Your code will be difficult to work with because you don't have declared edges. One of the properties of an edge is "weight" but here you have it as location's property.
As for implementing "visited" -- this is a call-state not a graph wide state. But, by making it part of the Location you now have a state management problem; Imagine trying to "find" something again? You would have to reset the 'visited' property on every node or throw away and create the whole graph again. Very inefficient and error prone.
if you implement DFS, which is really easy recursively or even with a tail loop, you pass the "visited" state along with the dfs method call. Example:
public Location find(Integer locationId) {
Location result = null;
for(Location l : locations) {
// this hashset represents the visited state which only matters for this method call
result = dfs(new HashSet(),l,locationId);
if(result != null)
break;
}
return result;
}
Note that this next method is private.
private Location dfs(Set<Location> visitedAlready,Location current, Integer id){
if(current.id == id)
return current;
visitedAlready.add(current); // instead of your boolean
Location result = null;
for(Location l : current.locations) {
result = dfs(visitedAlready,l,id);
if(result != null)
break;
}
return result;
}
This is a rough outline. If you reach out to me in Java chat I will give more input and eventually something more slick and reusable. I make no claim the above DFS works. But it's close
I am not sure that I completely understand but do the names in the 'Exits' array become children nodes? Not sure what methods are on the Exit object or if this is even remotely the most efficient solution plus I can't check the syntax at the moment unfortunately.
The idea is that the method takes a node, finds the child node and then invokes the method on that node effectively recursively 'walking' down the hierarchy.
ArrarList<Location> allNodes
// Create children for the specified node
public void createChildNodes(node n){
// Fetch all available exits
for(Exit e : n.getExit()){
// Iterate through all possible nodes
for(tempNode : allNodes) {
// Check if the 'exit' node matches one of the available nodes
if(tempNode.getName().equals(e.getName()){
// Match found, add it
n.addChildNode(tempNode, tempNode.getDistance));
// Check for children nodes of the temp node
createChildNodes(tempNode);
}
}
}
}

Can't add nodes in my linked list (java)

I've been working on my add method for a couple of hours now and seem to have hit a roadblock. My method is supposed to search through every node in the list to see if there is a matching employee number and if there isn't, add the object in order of employee number.
Unfortunately I cant even seem to add a node to the beginning or end of my list. I think I understand the logic. I have to search through my list for find where I want the node, then all I have to do is have the new node's link point the already existing one. I think that I'm either not creating the nodes properly or not linking them properly. Every time I try to test my code though, only one node appears in my list.
import java.util.*;
public class HumanResources
{
private EmployeeNode first;
employee data = new employee();
private class EmployeeNode
{
//data members of employeenode
private EmployeeNode link;
employee data = new employee();
private EmployeeNode()
{
data = null;
link = null;
}
private EmployeeNode (employee emp)
{
data = emp;
link = null;
}
}
public EmployeeNode search (employee search)
{
EmployeeNode current = first;
if (first == null)
{ return null;}
while((present != null) && (present.data != search))
{
present = present.link;
}
return present;
}
private EmployeeNode nextInList(EmployeeNode x)
{
return x.link;
}
public boolean isEmpty()
{
return ( first == null );
} // end of isEmpty()
public HumanResources()
{
first = null;
}
public HumanResources ( employee x)
{
this.data = x;
}
public boolean addEmployee( employee emp)
{
EmployeeNode current = new EmployeeNode();
current = first;
if (current == null)
{
first = new EmployeeNode(emp);
return true;
}
else
{
while(current.link != null)
{
EmployeeNode temp = new EmployeeNode();
temp.data = emp;
temp.link = current;
}
return true;
}
}
public Employee findEmployee(String EmpNumber)
{
EmployeeNode current = first;
if(first == null)
{
return null;
}
else{
while (current != null)
{
public String toString()
{
EmployeeNode display;
display = first;
String temp = "";
while(display != null)
{
temp += display.data + "\n";
display = display.link;
}
return temp;
}
}
And here is my employee class
import java.util.*;
/**
This class manipulate information relating to employees
*/
public class employee {
private String empNumber;
private String name;
private String department;
private double salary;
/**
Zero parameter constructor that sets the values to null
*/
public employee()
{
empNumber = null;
name = null;
department = null;
salary = 0.0;
}
/**
Four parameter constructor to initialize the data members to the give values
#param kempnumber Employee's ID number
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public employee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
/**
copy constructor
*/
public employee (employee copy)
{
empNumber = copy.empNumber;
name = copy.name;
department = copy.department;
salary = copy.salary;
}
/**
Four parameter constructor to set data members to given value
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public void setEmployee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary)
{
this.salary = salary;
}
public String toString()
{
return (empNumber + " " + name + " " + department + " " +salary);
}
public boolean equals(employee compareto) {
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if (firstemployee == secondemployee) {
return true;
}
else {
return false;
}
}
public int compareTo(employee compareto)
{
int less = -1;
int same = 0;
int more = 1;
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if(firstemployee > secondemployee)
{
return more;
}
else if(firstemployee == secondemployee)
{
return same;
}
else
{
return less;
}
}
}
For the addEmployee method, if you are adding to the front of the list you shouldn't need a while loop at all. Your 'first' variable is presumably maintaining a reference to the front of the loop, so all you need to do is create the employee, update the links and point 'first' towards it. Something like this...
public boolean addEmployee( employee emp){
if (first == null) {
first = new EmployeeNode(emp);
return true;
}
else { // first must != null
EmployeeNode temp = new EmployeeNode(emp); //create the new employee
temp.link = first; // link the new employee to the old employee at the front of the list
first = temp; //update the new front of list to be the new employee
return true;
}
}
Keep in mind though if you want to add it to the end of the list, you will need a while loop to search through the list and find the end before creating the new employee and updating the links.
If your getting confused with the links, try stepping through the code and drawing out the nodes with lines to represent the links to help get you used to visualising the linked list.

Linkedlist implementation in Java Sorting not working

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.

Categories