Using Comparator Interface to sort an object list

The Comparator interface exists in JDK since version 1.2 so it’s a mature part of Java tool box. And it’s a useful Interface. It provides two methods: compare and equals. We can use these methods when we’d like to sort an Array or Collection. Wicked.

So let’s sort a List with full of Object references.

Need a POJO like this:

Beer
-name
-strong

And the task is we’d like to have the strongest beer because we haven’t got enough time so you know. This case we need a Comparator for the stength of beer:

class BeerStrongComparator implements Comparator<Beer> {

  public int compare(Beer b1, Beer b2) {
    return b1.getStrong() < b2.getStrong() ? -1
     : b1.getStrong() > b2.getStrong() ? 1 : 0;
  }

}

And finally the usage:

  Collections.sort(allBeersList, new BeerStrongComparator());

You just put the Comparator as a second parameter in Collections class sort static method.

Tagged , ,

How can you change two variables without temporary variable

This is one of my favourite interview questions. It’s a really simple question.

OK. Let’s see the typical wrong answer:

int a = 5;
int b = 6;

//store 'x' in a temp variable
int temp = a;
a = b;
b = temp;

This answer is wrong because it contains an unnecessary variable.

And there are some good solutions:

a = a * b;
b = a / b;
a = a / b;

or

a = a + b;
b = a - b;
a = a - b;

or

a ^= b;
b ^= a;
a ^= b;