1

在 myMap 和 myTreemap 上调用 .getClass() 时,将返回“class java.util.LinkedHashMap”和“class java.util.TreeMap”。尽管返回类型匹配,myMap 只能使用 map 接口中的方法。我听说这通过允许程序员轻松更改实现类型来简化编程。但是 - 如果我(似乎)只能访问接口中的方法,那么改变实现类型有什么好处呢?

另外 - myMap 是 myTreeMap 是根据它们的类类型排序的,但同样,类类型的方法呢?

import java.util.*;

public class Freq {
public static void main(String[] args) {

    Map<String, Integer> m = new HashMap<String, Integer>();

    for (String a : args) {
        Integer freq = m.get(a);
        m.put(a, (freq == null) ? 1 : freq + 1);
    }

    System.out.println(m.size() + " distinct words:");
    System.out.println(m);

    System.out.println();

    Map<String, Integer> myMap = new LinkedHashMap<String, Integer>(m);       
    System.out.println("map: " + myMap.getClass());
    //output is "map: class java.util.LinkedHashMap"
    //but, only the methods in the myMap interface can be accessed.

    System.out.println(myMap.toString());
    //output in order of appearance like a LinkedHashMap should.


    TreeMap<String, Integer> myTreemap = new TreeMap<String, Integer>(m);
    System.out.println("treemap: " + myTreemap.getClass());
    //output is "treemap: class java.util.TreeMap"
    //methods in the Map interface and myTreemap can be accessed.

    System.out.println(myTreemap.toString());
    //output in in alphabetical order like a treemap should.

    } 
}
4

3 回答 3

1

如果你看一个带有方法参数的例子,你会更好地理解接口的意义:

boolean validateMap(Map<String, Object> map) {
  return map.get("x") != null && map.get("y") != null;
}

请注意,此方法并不关心您传入的确切映射:它适用于任何类型。这就是多态的美妙之处。

于 2013-07-29T10:16:19.087 回答
1

接口是一个很棒的功能。想想看——假设你想实现一个使用 hashMap 的算法。之前在代码中,用户选择了在较早运行的算法中优化的哈希映射实现。如果你没有接口,(相反,如果接口的概念根本不存在......或者一组函数指针根本不存在),你将不得不创建你自己的新算法想为每个实现的哈希映射实现。那是很多冗余代码,而且可读性不强。

您并没有真正失去对底层方法的访问权限。但是,如果您想访问底层的 TreeMap 及其方法……您必须将其从地图转换为树形地图。

@suppressedwarnings
TreeMap treeMap = null;    
if(myMap instanceof TreeMap){
    treeMap = (TreeMap)myMap;
}
if(treeMap == null){
     return;
     //If it wasn't the correct type, then it could not safely be cast.
}
//Now, do treeMap stuff
treeMap.treeMapOnlyMethod();

使用 instanceof 通常表明设计不佳 - 相反,应该使用多态性。

于 2013-07-29T04:47:36.790 回答
1

我听说这通过允许程序员轻松更改实现类型来简化编程。

正确的。

但是 - 如果我(似乎)只能访问接口中的方法,那么改变实现类型有什么好处呢?

您可以使用相同的 API(由接口发布的 API)获得例如 Tree 或 Hash 变体,而只需在一处更改代码。如果您被允许使用类的非接口方法,您将不会获得这种好处:您也必须更改所有这些调用。

另外 - myMap 是 myTreeMap 是根据它们的类类型排序的,但同样,类类型的方法呢?

我不明白这个问题。他们呢?

于 2013-07-29T04:50:36.323 回答