首页 > 解决方案 > 使用 asList() 方法时出现编译器错误

问题描述

我正在尝试使用 Arrays.asList 方法来存储我从 txt 文件中读取的句子。但是,我收到编译错误,告诉我不兼容的类型以及如何没有实例。我假设我不小心遗漏了一些东西,或者我的一条线断了,所以任何帮助都将不胜感激。

public static void main(String[] args) throws IOException
   {
      Scanner kb = new Scanner(System.in);
      // Prompt user to enter file for reading
      System.out.print("Please enter the name of a file: ");
      String fileName = kb.nextLine();
      // Stores user's input file to open
      File file = new File(fileName);
      // Reads user's file
      Scanner inputFile = new Scanner(file);

      while(inputFile.hasNext())
      {
         String str = inputFile.nextLine();
         ArrayList<String> list = Arrays.asList(str.split("\\s*,\\s*")); 

这是我得到的错误

错误:不兼容的类型:不存在类型变量 T 的实例,因此 List 符合 ArrayList

标签: javastringarraylist

解决方案


您正在寻找List<String> list = Arrays.asList(str.split("\\s*,\\s*"));

您想获取列表而不是 ArrayList

编辑:抢不回来


推荐阅读