2012-12-01 185 views
1

我在读关于集合,当这个问题困扰着我。可以设置实例化吗?

以下是我写的测试我的疑问的代码。

public static void main(String[] args) {   
    TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); 
    tree.put(1, "1"); 
    tree.put(2, "2"); 
    Set<Integer> set = tree.keySet(); 
    System.out.println(set instanceof Set); 
    System.out.println(set instanceof HashSet); 
} 

结果:

真 假

上面代码中说,我的设置对象设置的实例。但Set是一个接口,它如何被实例化。我很困惑。 :(

回答

2

Set是一个接口,这样不行,你不能直接实例化。接口将是相当无用的,如果你不能有一个实例,但!通过tree.keySet()返回的实例是一些具体的实施Set接口

让我们的超级特殊,并期待在the TreeMap#keySet() source code:。

public Set<K> keySet() { 
    return navigableKeySet(); 
} 

好了,并没有告诉我们很多,我们需要深入:

public NavigableSet<K> navigableKeySet() { 
    KeySet<K> nks = navigableKeySet; 
    return (nks != null) ? nks : (navigableKeySet = new KeySet(this)); 
} 

所以返回的具体类型是KeySet!有你的Set接口的实现。 http://www.docjar.com/html/api/java/util/TreeMap.java.html#1021

这就解释了这一点:

System.out.println(set instanceof Set); // prints true 
System.out.println(set instanceof HashSet); // prints false 

Set是一个接口; HashSet是该接口的一个实现。 foo instanceof Settrue为每个实例的任何Set实现foo。我们已经确定由TreeMap#keySet()返回的对象的具体类型是KeySet而不是HashSet,因此可以解释为什么set instanceof HashSetfalse - 因为setKeySet,所以它不能是HashSet

如果仍然没有意义的你,read up on instanceof

instanceof运算符比较对象到指定的类型。您可以使用它来测试对象是否是类的实例,子类的实例或实现特定接口的类的实例。

+0

谢谢:) ....只有现在困扰我的事情是汉王我可以知道,如果这组命令或不??? – TiMuS

+0

通过阅读API文档! http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html#keySet%28%29 –

相关问题