Hello,
Using a Comparator and Iterator, I am trying to add objects into a linked list in order. So far, I have the following:
public class ComparatorClass implements Comparator<Integer> {
public int compare(Integer int1, Integer int2) {
return int1.compareTo(int2);
}
}
and:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
public class OrderedListInheritance implements LinkedList {
ArrayList<Object> myList = new ArrayList<Object>();
Comparator comp = new ComparatorClass();
OrderedListInheritance(Comparator c) {
this.comp = c;
}
@Override
public void add(Object o) {
addLast(o);
}
@Override
public void addAtIndex(int index, Object o) {
Iterator it = getIterator();
while (it.hasNext()) {
Object element = it.next();
if (comp.compare(element, o) < 0) {
}else if (comp.compare(element, o) == 0) {
}else{
myList.add(o);
}
}
}
@Override
public void addFirst(Object o) {
addAtIndex(0, o);
}
@Override
public void addLast(Object o) {
addAtIndex(myList.size(), o);
}
@Override
public Object get(int index) {
return myList.get(index);
}
@Override
public Iterator getIterator() {
Iterator iter = myList.iterator();
return iter;
}
@Override
public int indexOf(Object o) {
return myList.indexOf(o);
}
}
I am unsure how to use the Iterator in conjunction with the comparator to add each element to the Linked List in order. Can somebody help me with the logic?
Thanks!