This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Saturday, January 16, 2010

18 - Sorted Sets and a strange class - level basic - Java 1.6.0_17 - NB 6.8

COULD YOU NOTICE THAT I HAD TO PUT A SINGLE QUOTE IN FRONT OF THE GREATER SIGN OF THE GENERIC. IF I DON'T DO THAT I HAVE A PROBLEM WITH THE EDITOR !

This example illustrates the fact that the objects of a collection have to be mutually comparable. If not a ClassCastException is returned by compare. Book page 583.
In this example if the object you put in the TreeSet is the a String, the comparison is made on name of the class...

package treesets;

public class StrangeClass implements Comparable <Object'> {

    Object aStrangeObject;
    String name;

    StrangeClass(Object o) {
        aStrangeObject = o;
        if (o instanceof String) {
            name = (String) o;
        } else {
            name = o.getClass().getName();
        }
    }

    public int compareTo(Object o) {
            return name.compareTo(((StrangeClass)o).name);
    }

    public String toString() {
        if (aStrangeObject instanceof String) {
            return (String) aStrangeObject;
        }
        return name;
    }
}

package treesets;

import java.util.Set;
import java.util.TreeSet;

public class TestStrangeClass {

    public static void main(String[] args) {

        boolean[] ba = new boolean[5];

        //Set s = new HashSet();
        Set s = new TreeSet<StrangeClass'>();

        ba[0] = s.add(new StrangeClass(new String("c")));
        ba[1] = s.add(new StrangeClass(new Integer(42)));
        ba[2] = s.add(new StrangeClass(new String("b")));
        ba[3] = s.add(new StrangeClass("a"));
        ba[4] = s.add(new StrangeClass(new Object()));


        for (int x = 0; x < ba.length; x++) {
            System.out.println(ba[x]);
        }

        System.out.println("Display : ");
        for (Object o : s) {
            System.out.println(o);
        }
    }
}


run:
true
true
true
true
true
Display :
a
b
c
java.lang.Integer
java.lang.Object


No comments:

Post a Comment

Followers