Reputation:
I have random ID numbers assigned to my list items. I have a class containing the LinkedList, and a class representing the items in the list. This is what I have to do: The constructor in the LinkedList class should call a method to build a list of test data. These should be added to the LinkedList in sorted order. After building the test data for the LinkedList, the constructor should call a method to print the items in the list to the command line.
I have most of the code, I just can't figure out how to sort the ID numbers in order, and also how to insert a new item to the list in the correct order. BELOW IS THE CODE I NEED TO EDIT TO MAKE THIS WORK:
public boolean decideToInsert (Makeup ee) {
boolean decision = false;
//code goes here
return decision;
Here is the LinkedList
package model;
import java.util.LinkedList;
import java.util.ListIterator;
public class MakeupList {
private LinkedList <Makeup> makeList = new LinkedList<>();
public MakeupList(){
this.createMakeList();
this.printMakeList();
}
public void createMakeList(){
makeList.add(new Makeup("Natural Face", "Too Face"));
for (int i = 0; i<10; i++){
addMakeup (new Makeup ("Matte Lipstick", "MAC"));
}
}
public void addMakeup (Makeup newMake){
boolean makeupAdded = false;
boolean insertDecision = false;
ListIterator<Makeup> makeIterator = makeList.listIterator();
while (makeIterator.hasNext()){
insertDecision = makeIterator.next().decideToInsert(newMake);
if (insertDecision == true){
makeList.add(makeIterator.previousIndex(), newMake);
makeupAdded = true;
break;
}
}
if(!makeupAdded){
makeList.add(newMake);
}
}
public void printMakeList(){
ListIterator<Makeup> makeIterator = makeList.listIterator();
while(makeIterator.hasNext()){
System.out.println(makeIterator.next().toString());
}
}
}
Upvotes: 0
Views: 217
Reputation: 11
You can use the Comparable<T>
interface and Collections#sort
For example, implement the Comparable<Makeup>
interface into your Makeup
class, and in the method you receive
public int compareTo(Makeup o) {
}
Use the Integer#compare(int i1, int i2)
method to compare your two ids, return the value you receive from Integer compare.
Then simply use Collections#sort(List<T>)
to sort your list.
Depending on the order you put i1 and i2 in you will receive an ascending or descending list, so play around until you get it right.
Upvotes: 1
Reputation: 76
Edit your current code is not enough to make your requirements work. you have to add few new functions for the LinkedList
For example, a function for insert object in the different index. A function for delete objects in the LinkedList.
I recommend you to create a Class called Comparator which can compare two objects and return the larger object. Use the comparator with different sorting algorithms. If you don't know any sorting algorithms, bubble sort is the easiest way for sorting.
BTW, the best way is to use Binary Tree if you know what is it.
Upvotes: 0