如何使instanceof区分子类和父类?

时间:2015-03-26 15:53:33

标签: java inheritance instanceof

在java LinkedHashSet扩展HashSet 我的代码写为:

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);
    }
}

使用以下输出:

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.

显示方法在检查&#34; X&#34;之后打印输出。是&#34; Y&#34;。的一个实例 第一个if-else的输出相同,因为LinkedHashSet扩展了HashSet。怎么解决这个问题?

1 个答案:

答案 0 :(得分:6)

首先测试子类LinkedHashSet,即

    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.");