Search⌘ K
AI Features

More on Interfaces

Explore the Java Comparator interface to specify custom ordering for objects beyond their natural order. Understand how to implement comparators, manage null values, and override default sort behavior using functional interfaces.

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 private in Java?

A.

Yes, but only since Java 9, and only for internal use within the interface.

B.

No, interface methods cannot be private.


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 ...