Java 类型不匹配:无法从列表转换<;字符串>;到ArrayList<;字符串>;
在编译代码的过程中,我遇到了“类型不匹配”的问题。实际上我不知道为什么列表不能转换为ArrayList。我使用java.util.Collections.singletonList并希望转换为列表 我已尝试将表达式强制转换为ArrayList,但无法强制转换Java 类型不匹配:无法从列表转换<;字符串>;到ArrayList<;字符串>;,java,list,arraylist,collections,Java,List,Arraylist,Collections,在编译代码的过程中,我遇到了“类型不匹配”的问题。实际上我不知道为什么列表不能转换为ArrayList。我使用java.util.Collections.singletonList并希望转换为列表 我已尝试将表达式强制转换为ArrayList,但无法强制转换 public class AlphabeticShifts { public static ArrayList<String> DoAlphapeticShifts(ArrayList<String> s
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"));
}
}
公共类字母移位{
公共静态ArrayList DoalPhapeticshift(ArrayList语句){
Collections.sort(句子、字符串、不区分大小写的顺序);
返回句子;
}
公共静态void main(字符串[]args){
doalphapecticshift(java.util.Collections.singletonList(“数组”);
}
}
例外情况:
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)
java.lang.Error:未解决的编译问题:
字母移位类型中的方法DOALPHAPICSHIFTS(ArrayList)不适用于参数(列表)
类型不匹配:无法从列表转换为ArrayList
位于AlphapsShift.main(AlphapsShift.java:15)
ArrayList
是接口列表
的子类。因此,我们可以将ArrayList
转换为List
,因为我们知道ArrayList
实现了List
的所有方法(当然,它是一个接口)
但是如果我们试图从List
转换到ArrayList
,List
只是一个接口,所以我们不能降级,因为我们根本不知道该列表是否是ArrayList
的子类
本质上,
ArrayList
是列表的一种特定类型。因此,由于我们不确定该List
是否确实是ArrayList
,编译器无法确定这是否是有效的强制转换。如果要排序并返回字符串的常规列表,保留参数的类型,请将方法签名更改为:
public static <L extends List<String>> L DoAlphapeticShifts(L sentences) {
publicstaticl-doalphapecticshift(L句){