Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用接口和具体类实例化之间的区别?(HashMap、Map&;List、ArrayList)_Java_Dictionary_Arraylist_Collections_Hashmap - Fatal编程技术网

Java 使用接口和具体类实例化之间的区别?(HashMap、Map&;List、ArrayList)

Java 使用接口和具体类实例化之间的区别?(HashMap、Map&;List、ArrayList),java,dictionary,arraylist,collections,hashmap,Java,Dictionary,Arraylist,Collections,Hashmap,我知道List和Map是可以实现的接口,ArrayList和HashMap是可以创建和使用其对象的类 我知道这两对的区别。我的实际问题是,以下两种说法有区别吗 HashMap< K, V> myMap = new HashMap<K, V>(); Map< K, V> myMap = new HashMap<K, V>(); HashMapmyMap=newhashmap(); MapmyMap=newhashmap(); 如果有,那么有什

我知道
List
Map
是可以实现的接口,
ArrayList
HashMap
是可以创建和使用其对象的类

我知道这两对的区别。我的实际问题是,以下两种说法有区别吗

HashMap< K, V>  myMap = new HashMap<K, V>(); 
Map< K, V> myMap = new HashMap<K, V>();
HashMapmyMap=newhashmap();
MapmyMap=newhashmap();
如果有,那么有什么区别,什么时候我应该使用哪一种?同样,以下两者之间的区别是什么:

ArrayList< Integer> myList = new ArrayList<Integer>();
List< Integer> myList = new ArrayList<Integer>();
ArrayListmyList=newarraylist();
ListmyList=newarraylist();

ArrayList
列表
接口的具体实现

所以区别在于一个有具体的类引用,另一个有接口引用

HashMap< K, V>  myMap = new HashMap<K, V>(); //reference of concrete class HashMap
Map< K, V>  myMap = new HashMap<K, V>(); //reference of interface Map
HashMapmyMap=newhashmap()//具体类HashMap的引用
MapmyMap=newhashmap()//接口图的参考
您应该始终尝试使用接口编程

注意:当您通过时,应使用带有接口的程序
Map
在其他地方,对于局部变量,您可以自由使用具体变量 实施


另一个区别是,在
Map
one上,您将无法调用
HashMap
ArrayList
的方法,它是
列表
接口的具体实现

HashMap< K, V> myMap = new HashMap(); 
所以区别在于一个有具体的类引用,另一个有接口引用

HashMap< K, V>  myMap = new HashMap<K, V>(); //reference of concrete class HashMap
Map< K, V>  myMap = new HashMap<K, V>(); //reference of interface Map
HashMapmyMap=newhashmap()//具体类HashMap的引用
MapmyMap=newhashmap()//接口图的参考
您应该始终尝试使用接口编程

注意:当您通过时,应使用带有接口的程序
Map
在其他地方,对于局部变量,您可以自由使用具体变量 实施

另一个区别是,在
Map
one上,您将无法调用
HashMap

HashMap< K, V> myMap = new HashMap(); 
正在创建带有具体实现的
Map
实例,称为使用接口编程

第二种方式,即,将模块化引入程序

这里有一个很好的解释,关于什么是好处以及什么时候去做:

正在创建带有具体实现的
Map
实例,称为使用接口编程

第二种方式,即,将模块化引入程序

这里有一个很好的解释,关于什么是好处以及什么时候去做:


我什么时候应该使用哪一种?哪一个在代码设计方面最好?@786是的,总是喜欢使用界面代码。请参阅链接并接受asnwer。我什么时候应该使用哪一个?哪一个在代码设计方面最好?@786是的,总是喜欢使用接口进行代码设计。请参阅链接并接受asnwer.+1,因为您应该始终尝试使用接口进行编程+1,因为您应该始终尝试使用接口进行编程