0

Some external function to me gives me a java.io.File instance, but I would like to change default behavior for compareTo for that instance on-the-fly. Whats the best approach?

The only thing I can think of is wrapping this File instance into a

public class FileWrapper extends File{   

    FileWrapper(File in){
        //Assign var to the global var      
    }

    @Overrides
    public compareTo(File in){ return whatever;}

}

And make all methods override File´s ones and forward the calls to the global wrapped instance pased through constructor, but it´s very ugly...

Maybe I am forgetting some other easier way...

Whimusical
  • 6,401
  • 11
  • 62
  • 105
  • What is an anonymous *function* in Java? – adarshr May 31 '12 at 09:50
  • Sorry I meant a function inside an anonymous class – Whimusical May 31 '12 at 09:52
  • 1
    I'm not sure this is going to work any way you try to make it. `compareTo` is required to be commutative: `File.compareTo(FileWrapper)` has to be symmetric with `FileWrapper.compareTo(File)`, but you can't control `File.compareTo(FileWrapper)`. – Louis Wasserman May 31 '12 at 10:02

1 Answers1

3

The only reason you might want to use the compareTo method is to sort a collection.

You can always create a Comparator and pass it into a Collections.sort call.

Collections.sort(myList, new Comparator<File>() {
    public int compare(File file1, File file2) {
        // write your custom compare logic here.
    }
});

Even if you use a sorted-collection such as TreeSet, it already provides you with an overloaded constructor for passing in the Comparator.

/**
 * Constructs a new, empty tree set, sorted according to the specified
 * comparator.  All elements inserted into the set must be <i>mutually
 * comparable</i> by the specified comparator: {@code comparator.compare(e1,
 * e2)} must not throw a {@code ClassCastException} for any elements
 * {@code e1} and {@code e2} in the set.  If the user attempts to add
 * an element to the set that violates this constraint, the
 * {@code add} call will throw a {@code ClassCastException}.
 *
 * @param comparator the comparator that will be used to order this set.
 *        If {@code null}, the {@linkplain Comparable natural
 *        ordering} of the elements will be used.
 */
public TreeSet(Comparator<? super E> comparator) {
    this(new TreeMap<E,Object>(comparator));
}
adarshr
  • 61,315
  • 23
  • 138
  • 167