Search⌘ K
AI Features

More on Interfaces

Explore the use of the Comparator functional interface in Java to customize object ordering beyond natural order. Understand how Comparator allows sorting with or without implementing Comparable and how it handles null values differently. This lesson helps you grasp practical interface applications in Java programming.

We'll cover the following...

1.

Is the complexity of the following code snippet O(n) always?

    void printName(List<String> names) {
        for(int i=0; i<names.size(); i++) {
            System.out.println(names.get(i));
        }
    }
Show Answer
1 / 2
Technical Quiz
1.

Can the methods of an interface be made private?

A.

Yes

B.

No


1 / 2
Java
class Demonstration implements InterfaceWithStaticMethod{
public static void main( String args[] ) {
printName();
InterfaceWithStaticMethod.printName();
}
public static void printName() {
System.out.println("Demonstration class");
}
}
interface InterfaceWithStaticMethod {
static void printName() {
System.out.println("Interface with InterfaceWithStaticMethod");
}
}
1.

What is the difference between Comparable and Comparator interfaces?

Show Answer
Did you find this helpful?
Java
import java.math.BigDecimal;
import java.util.*;
class Demonstration {
public static void main( String args[] ) {
BigDecimal val1 = new BigDecimal("4.0");
BigDecimal val2 = new BigDecimal("4.00");
// Equals returns false because of differing precision
System.out.println("val1.equals(val2) = " + val1.equals(val2));
// CompareTo returns 0 implying both objects are equal
System.out.println("val1.compareTo(val2) = " + val1.compareTo(val2));
// HashSet uses equals() method and ends up storing
// two objects
Set<BigDecimal> hashSet = new HashSet<>();
hashSet.add(val1);
hashSet.add(val2);
System.out.println("hashSet.size() = " + hashSet.size());
// TreeSet uses compareTo() method and ends up storing
// a single object
Set<BigDecimal> treeSet = new TreeSet<>();
treeSet.add(val1);
treeSet.add(val2);
System.out.println("treeSet.size() = " + treeSet.size());
}
}

The Comparator is a functional interface that can be used to specify an ordering relation between the elements of a type other than their ...