【问题标题】:Syntax error on token ".", @ expected after this token [duplicate]令牌“。”上的语法错误,此令牌后应为@ [重复]
【发布时间】:2019-10-22 07:52:14
【问题描述】:
public class ListFile {
    public static void main(String[] args){
        String[] arr = {"text", "tekl"};
        List<String> list = Arrays.asList(arr);     
        List<String> listt = Arrays.asList({"text", "tttt"});
        }
}

第 4 行完全正常。但是,第 5 行在第 36 列给出了错误:“标记“。”的语法错误,@ 预期在此标记之后”。 作为{"text", "tttt"} 传递的参数是否在这里被视为块?

【问题讨论】:

  • 试试Arrays.asList(new String[]{"text", "tttt"})

标签: java arrays list


【解决方案1】:

当您执行Type[] arr = { …, … }; 时,即为array initializer。它只能在数组声明中使用(或在数组创建表达式中,即new String[]{"a", "b"})。

Arrays.asList 被定义为采用可变参数 (asList(T... a)),因此您不必先将参数包装在数组中:Arrays.asList("text", "tek1") 已经从您的参数隐式创建一个数组并将其传递给方法.

【讨论】:

    【解决方案2】:

    您正在混合可能的正确合成器。这些是您要指定的可能性:

    List<String> listt = Arrays.asList("text", "tttt");
    

    List<String> listt = Arrays.asList(new String[]{"text", "tttt"});
    

    【讨论】:

      【解决方案3】:

      您尝试在 Arrays.asList 中插入无效的内容。 尝试使用

      List<String> listt = Arrays.asList("text", "tttt");
      

      来自 Java 8 javadocs

      asList

      @SafeVarargs

      public static List asList(T...a)

      返回由指定数组支持的固定大小的列表。 (将返回的列表“写入”到数组的更改。)此方法起作用 作为基于数组和基于集合的 API 之间的桥梁,在 与 Collection.toArray() 结合。返回的列表是 可序列化并实现 RandomAccess。

      此方法还提供了一种方便的方法来创建一个固定大小的列表,该列表已初始化为包含多个元素:

      List stooges = Arrays.asList("Larry", "Moe", "Curly");

      类型参数:

      T - 数组中对象的类别

      参数:

      a - 支持列表的数组

      返回:

      指定数组的列表视图

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-27
        相关资源
        最近更新 更多