Question

I'm working on a sorted Linked List homework and confused about setting up a comparator. I've written a linked list class that is parametrized to accept any class. The linked list works fine but I'm confused about how to set a comparator for the list because it is parametrized. Do I first make a comparator class and pass it in to a constructor? The comparator will be used to maintain an ordering of the list. Or do I need to have a variable inside the class that I set that changes the behavior of a comparator defined in the linked list class? Sorry if this doesn't make very much sense as I am slightly confused. Thanks!

EDIT:

I should have clarified, we are not allowed to use the LinkedList from the Java collections library, we are designing our own (yes I know I would not do that in practice, but it is a homework design exorcize). My LinkedList class looks somewhat like this:

public class LinkedList<T> implements Iterable<T> {
    private LinkedListNode<T> head = null;
    private int size = 0;
        .
        .
        .
        //various methods for retrieving size, iterator etc...
}

Upon insertion of an element, it should be placed in the correct spot. My idea is to have this determined by a comparator that is passed in upon instantiation of an LinkedList object. Maybe something like this:

LinkedList<MyClass> myList(MyClass.myComparator);

My issue is that I need to have multiple comparators for the same class (MyClass) that are used throughout the lifetime of the object. I'm also confused as how to set the comparator in LinkedList after having it passed in.

Was it helpful?

Solution

LinkedList is not a sorted collection, so you cannot pass it a Comparator during construction. Observe that none of its constructors take a Comparator.

Instead, you would build it and add to it, and then use

Collections.sort(myList, new MyComparator());

You can make a write a Comparator of a parameterized type T with the following syntax.

public class MyComparator implements Comparator<T>() {
      public int compare (T a, T b) {
          // Put comparison logic here.
      }
}

Obviously, you want to replace T above with the name of your type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top