我在代码编译过程中遇到了“类型不匹配”问题。其实我不知道为什么List不能转换为ArrayList。我使用了 java.util.Collections.singletonList 并想转换为列表。
我尝试将表达式转换为 ArrayList,但无法转换。
public class AlphabeticShifts {
public static ArrayList<String> DoAlphapeticShifts(ArrayList<String> sentences) {
Collections.sort(sentences, String.CASE_INSENSITIVE_ORDER);
return sentences;
}
public static void main(String[] args){
DoAlphapeticShifts(java.util.Collections.singletonList("Array"));
}
}
异常(exception):
java.lang.Error: Unresolved compilation problems:
The method DoAlphapeticShifts(ArrayList<String>) in the type AlphabeticShifts is not applicable for the arguments (List<String>)
Type mismatch: cannot convert from List<String> to ArrayList<String>
at AlphabeticShifts.main(AlphabeticShifts.java:15)
最佳答案
ArrayList
是接口(interface)List
的子类。因此,我们可以将 ArrayList
转换为 List
,因为我们知道 ArrayList
实现了 List
的所有功能。 s 方法(当然,它是一个接口(interface))
但是,如果我们尝试从 List
转换为 ArrayList
,List
只是一个接口(interface),因此我们无法降级,因为我们不这样做根本不知道该列表是否是 ArrayList 的子类。
本质上,ArrayList
是List
的一种特定类型。因此,由于我们不确定 List
是否绝对是 ArrayList
,编译器无法确定这是否是有效的转换。
关于java - 类型不匹配 : cannot convert from List<String> to ArrayList<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57047222/