Instance Variable vs Local Variable

From: Paul Carey (ociardhp_at_online.ie)
Date: 12/03/03


Date: 3 Dec 2003 06:44:16 -0800

Hi

When delegating a compareTo method for a playing card to a Comparator, I
wasn't sure whether to go for the instance variable or local variable approach:

public class Card implements Comparable
{
    static class SortByValueThenSuit implements Comparator
    {
        public int compare(Object o1, Object o2)
        {
            ...
        }
    }

    // local variable approach
    public int compareTo(Object o)
    {
        return new SortByValueThenSuit().compare(this, o);
    }
    
    
    // instance variable approach
    private SortByValueThenSuit sorter = new SortByValueThenSuit();
    public int compareTo(Object o)
    {
        return sorter.compare(this, o);
    }
}

With only 52 cards in the deck and with a fairly limited number of comparisons,
maybe the local variable option would be considered better for reasons of
encapsulation and because the Comparator will be automatically marked for
garbage collection once the method has exited. But I'm curious to know under
what kind of circumstances might the overhead of creating a new Comparator
every time compareTo is invoked mean that the instance variable approach
would be preferable. If there are a very large number of objects to be sorted
and sorting occurs regularly, am I going to be wasting memory, or is the fact
that the Comparator contains no instance variables itself relevant?

Many thanks

Paul



Relevant Pages

  • Re: Instance Variable vs Local Variable
    ... turned out to be usefully faster then you'd keep the optimisation. ... another card. ... Or we could make a reversed SortedSet of Cards using the our own comparator ...
    (comp.lang.java.programmer)
  • Re: Object to Comparable
    ... compareTo method that takes one argument, ... certainly not of the same class as the Comparator; ... rather than unspecialized Object references. ... plain Comparable or plain Comparator is now passé. ...
    (comp.lang.java.help)
  • Re: Sorting based on multiple parameters
    ... Comparator interface has no compareTo method. ... int compareTo. ... Sorry for confusion...I meant compare method of Comparator. ...
    (comp.lang.java.programmer)
  • Re: sorting
    ... I've always found the best way to sort a list is to use ... Collections.sort (List, Comparator). ... objects to Comparable and use the compareTo method. ... if don't know what your Object is other than it's one of the standards ...
    (comp.lang.java.programmer)