【问题标题】:Type mismatch: cannot convert from List<String> to ArrayList<String> [duplicate]类型不匹配:无法从 List<String> 转换为 ArrayList<String> [重复]
【发布时间】:2019-11-24 14:20:40
【问题描述】:

我在编译代码的过程中遇到了“类型不匹配”的问题。其实我不知道为什么 List 不能转换为 ArrayList。我使用了 java.util.Collections.singletonList 并想转换为 List。

我尝试将表达式转换为 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"));
    }
}

例外:

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 list arraylist collections


    【解决方案1】:

    ArrayList 是接口List 的子类。因此我们可以将ArrayList 转换为List,因为我们知道ArrayList 实现了List 的所有方法(当然,它是一个接口)

    但是如果我们尝试从List 转换为ArrayListList 只是一个接口,所以我们不能降级,因为我们根本不知道该列表是否是ArrayList 的子类.

    本质上,ArrayListList 的特定类型。因此,由于我们不确定 List 是否肯定是 ArrayList,编译器无法确定这是否是有效的转换。

    【讨论】:

      【解决方案2】:

      如果要排序并返回一般字符串列表,保留参数的类型,请将方法签名更改为:

      public static <L extends List<String>> L DoAlphapeticShifts(L sentences) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多