Java 中的数组列表和列表
Arraylist and List in Java
谁能解释一下下面代码的含义,尤其是ArrayList和List,为什么我们需要同时使用两者?
String [] forecastArray =
{
"Today - Sunny - 35/30",
"Tomorrow - Foggy - 33/28",
"Wednesday - Cloudy - 33/26",
"Thursday - Sleepy - 30/24",
"Friday - Bunking - 36/34",
"Saturday - Trapped - 38/35",
"Sunday - Heavy Rain - 32/28"
};
List<String> myList = Arrays.asList(forecastArray);
List<String> weekForecast = new ArrayList<>(myList);
List
is an interface. ArrayList
is an implementation of that interface. It's generally recommended to program to the interface. That way you could switch to a LinkedList
and not change a return type or other code later on. This is an example of polymorphism.
Elliot Frish 已经清楚地解释了第一部分。
在您的具体情况下,
List<String> myList = Arrays.asList(forecastArray);
List<String> weekForecast = new ArrayList<>(myList);
不一样。
因为 Arrays.asList
返回的 List
实例与 java.utils.ArrayList
不同。 ArrayList
返回的是 Arrays
里面的一个 private static class
class.
由于ArrayList
s(在数组和集合中)实现 List
接口,你可以将它们分配给List
. 接口代码 :)
注意:ArrayList<String> myList = Arrays.asList(someArray);
--> 不编译
列表是一个接口。 ArrayList 是该接口的一个实现。
基本上这里 Arrays.asList(forecastArray) 方法 returns 一个列表,但调用者不知道哪个实例是 returns。所以首先分配给列表然后尝试初始化 Arraylist。
或者您可以如下所示进行操作。
List weekForecast = new ArrayList(Arrays.asList(forecastArray));
谁能解释一下下面代码的含义,尤其是ArrayList和List,为什么我们需要同时使用两者?
String [] forecastArray =
{
"Today - Sunny - 35/30",
"Tomorrow - Foggy - 33/28",
"Wednesday - Cloudy - 33/26",
"Thursday - Sleepy - 30/24",
"Friday - Bunking - 36/34",
"Saturday - Trapped - 38/35",
"Sunday - Heavy Rain - 32/28"
};
List<String> myList = Arrays.asList(forecastArray);
List<String> weekForecast = new ArrayList<>(myList);
List
is an interface. ArrayList
is an implementation of that interface. It's generally recommended to program to the interface. That way you could switch to a LinkedList
and not change a return type or other code later on. This is an example of polymorphism.
Elliot Frish 已经清楚地解释了第一部分。
在您的具体情况下,
List<String> myList = Arrays.asList(forecastArray);
List<String> weekForecast = new ArrayList<>(myList);
不一样。
因为 Arrays.asList
返回的 List
实例与 java.utils.ArrayList
不同。 ArrayList
返回的是 Arrays
里面的一个 private static class
class.
由于ArrayList
s(在数组和集合中)实现 List
接口,你可以将它们分配给List
. 接口代码 :)
注意:ArrayList<String> myList = Arrays.asList(someArray);
--> 不编译
列表是一个接口。 ArrayList 是该接口的一个实现。
基本上这里 Arrays.asList(forecastArray) 方法 returns 一个列表,但调用者不知道哪个实例是 returns。所以首先分配给列表然后尝试初始化 Arraylist。
或者您可以如下所示进行操作。
List weekForecast = new ArrayList(Arrays.asList(forecastArray));