Collections & Sorting

Stamp Collector

Collections is a class with only static methods, devoted to operations on objects with collecting characteristics, List, Map, and Set. It can:

  • copy collections
  • put all contents of a collection into another
  • sort collections
  • reverse the order of collections
  • randomly shuffle a collection
  • find frequency of elements
  • and more, but perhaps the most often used is sort.

Sorting our objects can be done by three standard methods:

  • equals()
  • compareTo()
  • compare()

The latter two are the ways that Collections uses to sort data.

 

equals()

This is a method included with class Object, so therefore it is included with every type of object.

It returns a boolean value (true or false) saying whether this object is “equal” with another.

It can and is expected to be overridden to compare objects by your customized way.

Example (try it):

class Cat
{
   int age;
   Cat(int age)
   {
      this.age = age;
   }

   public boolean equals(Cat other)
   {
      return this.age == other.age;
   }
}

 

compareTo()

This method comes from the java.lang.Comparable<T> interface:

int compareTo(T object)

is implemented to compare this object with another to give a negative value for this object being less than, 0 for equals, or positive value for greater than the other.

This is the more convenient compare method, but must be implemented in every class you want to compare.

Example (try it):

class Cat implements Comparable<Cat>
{
   int age;
   Cat(int age)
   {
      this.age = age;
   }
 
   public int compareTo(Cat other)
   {
      if (this.age < other.age)
       return -1;
      else if (this.age == other.age)
       return 0;
      else
       return 1;
   }
}

Note that a simpler way to write the method above is:

return this.age - other.age; //- value for <, 0 for ==, + value for >

 

READ  Operators

compare()

This method comes from the java.util.Comparator<T> interface:

int compare(T obj1, T obj2)

is implemented in a separate class that compares another class’s objects to give a negative value for the first object being less than, 0 for equals, or positive value for greater than the second object.

It is needed when you cannot make a class implement compareTo() because it is not modifiable. It is also used when you want different ways to compare objects, not just one (such as by name or age)..

Example (try it):

class Cat
{
   int age;
   Cat(int age)
   {
      this.age = age;
   }
}

class CatComparatorByAge implements Comparator<Cat>
{
   public int compare(Cat first, Cat second)
   {
      if (first.age < second.age)
         return -1;
      else if (first.age == second.age)
         return 0;
      else
         return 1;
   }
}
Please like & share: