Siddharth Thevaril
Siddharth Thevaril

Reputation: 3788

How to make instanceof differentiate between sub-class and parent-class?

In java LinkedHashSet extends HashSet I have a code written as:

import java.util.*;
class SetInterfaceUsage
{
    static <Obj> void display(Obj myList)
    {
        if(myList instanceof HashSet)
            System.out.println("Hash Set contains : " + myList + " ......order based on Hashing");
        else if(myList instanceof LinkedHashSet)
            System.out.println("Linked List contains : " + myList + " ......In inserted order.");
        else if(myList instanceof TreeSet)
            System.out.println("Tree Set contains : " + myList + " ......Ascending order.");
    }
    public static void main(String X[])
    {
        /*  HashSet */
        Set hs = new HashSet();
        hs.add(2001);
        hs.add(':');
        hs.add('A');
        hs.add("Space Odyssey");
        hs.add(2002);
        hs.add("0");
        display(hs);

        /*  Linked Hash Set */
        Set lhs = new LinkedHashSet();
        lhs.add(2001);
        lhs.add(':');
        lhs.add('A');
        lhs.add("Space Odyssey");
        lhs.add(2002);
        lhs.add("0");
        display(lhs);

        /* Tree Set */  /*  All Strings */
        Set ts = new TreeSet();
        ts.add("2001");
        ts.add(":");
        ts.add("A");
        ts.add("Space Odyssey");
        ts.add("2002");
        ts.add("0");
        display(ts);
    }
}

with the following output :

Hash Set contains : [2002, 0, 2001, A, :, Space Odyssey] ......order based on Hashing
Hash Set contains : [2001, :, A, Space Odyssey, 2002, 0] ......order based on Hashing
Tree Set contains : [0, 2001, 2002, :, A, Space Odyssey] ......Ascending order.

The display method prints output after checking whether "X" is an instance of class "Y".
The output of the first if-else is the same because LinkedHashSet extends HashSet. How to solve this?

Upvotes: 1

Views: 640

Answers (1)

T.Gounelle
T.Gounelle

Reputation: 6033

Just test the subclass LinkedHashSet first, i.e.

    if(myList instanceof LinkedHashSet)
        System.out.println("Hash Set contains : " + myList + " ......order based on Hashing");
    else if(myList instanceof HashSet)
        System.out.println("Linked List contains : " + myList + " ......In inserted order.");
    else if(myList instanceof TreeSet)
        System.out.println("Tree Set contains : " + myList + " ......Ascending order.");

Upvotes: 6

Related Questions