Saturday, August 21, 2010

Comparator: AddStuff.java

Courtesy of Sun Web Learning Center

1. import java.util.*;
2. class Stuff implements Comparator {
3.   int x;
4.   Stuff(int x) { this.x = x; }
5.   public int compareTo(Object o) { return this.x - ((Stuff)o).x; }
6. }
7. class AddStuff {
8.   public static void main(String [] args) {
9.     TreeSet<Stuff> ts = new TreeSet<Stuff>();
10.     ts.add(new Stuff(1));
11.     ts.add(new Stuff(2));
12.     System.out.println(ts.size());
13. } }

What is the result?

A     0
B     1
C     2
D     Compilation fails.
E     An exception is thrown at runtime.

D is correct. Since Stuff implements Comparator, it must implement a compare method.

No comments:

Post a Comment