Swap Two Numbers without Temp or Third variable

int a = 10;
int b = 20;
System.out.println("value of a and b before swapping, a: " + a +" b: " + b);

//swapping value of two numbers without using temp variable
a = a+ b; //now a is 30 and b is 20
b = a -b; //now a is 30 but b is 10 (original value of a)
a = a -b; //now a is 20 and b is 10, numbers are swapped
System.out.println("value of a and b after swapping, a: " + a +" b: " + b);
int a = 6;
int b = 3;
System.out.println("value of a and b before swapping, a: " + a +" b: " + b);

//swapping value of two numbers without using temp variable using multiplication and division
a = a*b; //now a is 18 and b is 3
b = a/b; //now a is 18 but b is 6 (original value of a)
a = a/b; //now a is 3 and b is 6, numbers are swapped
System.out.println("value of a and b after swapping using multiplication and division, a: " + a +" b: " + b);
Swap Two Numbers without Temp or Third variable

Example to sort an arraylist of objects by a property

Comparable

A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.

Comparator

A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.

 

class HockeyPlayer {
    public final int goalsScored;
    // ...
};

List<HockeyPlayer> players = // ...

Collections.sort(players, new Comparator<HockeyPlayer>() {
    @Override 
    public int compare(HockeyPlayer p1, HockeyPlayer p2) {
        return p1.goalsScored - p2.goalsScored; // Ascending
    }
});
class PlayerComparatorByRating implements Comparator<Player> {
    @Override
    public int compare(Player o1, Player o2) {
        return o1.getRating() - o2.getRating();
    }
}

class PlayerComparatorByName implements Comparator<Player> {
    @Override
    public int compare(Player o1, Player o2) {
        return o1.getName().compareTo(o2.getName());
    }
}
Collections.sort(list, new PlayerComparatorByRating());
System.out.println(list);
Collections.sort(list, new PlayerComparatorByName());
System.out.println(list);
List<Book> books = new ArrayList<Book>();
Collections.sort(books, new Comparator<Book>(){
    public int compare(Book o1, Book o2) {
        return o1.name.compareTo(o2.name);
    }
});
Example to sort an arraylist of objects by a property