我知道List
和Map
是可以实现的接口(interface),ArrayList
和HashMap
是可以创建和使用其对象的类。
我知道这两对之间的区别。我的实际问题是,以下两个陈述之间有区别吗?
HashMap< K, V> myMap = new HashMap<K, V>();
Map< K, V> myMap = new HashMap<K, V>();
如果有,那么有什么区别,什么时候应该使用哪一个?同样,有什么区别:
ArrayList< Integer> myList = new ArrayList<Integer>();
List< Integer> myList = new ArrayList<Integer>();
最佳答案
HashMap< K, V> myMap = new HashMap();
正在创建一个HashMap
实例,正如您在Java中的任何地方看到的那样。
鉴于:
Map< K, V> myMap = new HashMap();
正在创建一个带有具体实现的Map
实例,称为接口(interface)编程。
第二种方式,即Programming with interfaces ,为您的程序带来模块化。
这里有一个很好的解释,关于它的好处是什么以及何时使用它:
What is the benefit of polymorphism using Collection interface to create ArrayList object?
关于java - 使用接口(interface)实例化和具体类实例化之间的区别? (HashMap、Map & List、ArrayList),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18802190/