Skip to main content

Posts

Showing posts from December 3, 2009

java.lang.Comparator Vs java.lang.Comparable

What are Java Comparators and Comparables? As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be sorted according to a predefined order. Two of these concepts can be explained as follows. 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.lang.Comparator interface. How to use these? There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user. Those are; java.lang.Comparable: int compareTo(Object o1) This method compares this object with o1 object. Returned int value has the following meanings. 1. positiv...

Linked List Example

/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ /** * This class implements a linked list that can contain any type of object that * implements the nested Linkable interface. Note that the methods are all * synchronized, so that it can safely be used by multiple threads at the same * time. */ public class LinkedList { /** * This interface defines the methods required by any object that can be * linked into a linked list. */ public interface Linkable { public Linkable getNext(); // Returns the next element in the list public...

Sorting an List in Java

// Create a list String[] strArray = new String[] {"z", "a", "C"}; List list = Arrays.asList(strArray); // Sort Collections.sort(list); // C, a, z // Case-insensitive sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); // a, C, z // Reverse-order sort Collections.sort(list, Collections.reverseOrder()); // z, a, C // Case-insensitive reverse-order sort Collections.sort(list, String.CASE_INSENSITIVE_ORDER); Collections.reverse(list); // z, C, a