读取文本文件并返回ArrayList类型对象的Java方法 publicstaticvoidmain(字符串[]args) { ArrayList LocationsList=readFile(“Locations.csv”,“Locations”); //ArrayList MoviesList=readFile(“Movies.csv”、“Movies”); //ArrayList OperatorList=readFile(“Operators.csv”、“Operators”); //ArrayList PersonCategoryList=readFile(“PersonCategory.csv”,“PersonCategory”); } 公共静态ArrayList读取文件(字符串文件名,字符串whichFile) { ArrayList=新建ArrayList(); 尝试 { BufferedReader br=新的BufferedReader(新文件读取器(文件名)); 字符串indata; 内线=0; 而((indata=br.readLine())!=null) { StringTokenizer st=新的StringTokenizer(indata,“,”); 如果(行!=0) { 如果(whichFile.equals(“位置”)) { int id=Integer.parseInt(st.nextToken()); 字符串city=st.nextToken(); 如果(city.charAt(0)='“') { 字符串c=st.nextToken(); city=city.substring(1,city.length())+“,”+c.substring(0,c.length()-1); } int stateId=Integer.parseInt(st.nextToken()); 地点x=新地点(id、城市、州id); 增加(x); } else if(whichFile.equals(“电影”)) { int id=Integer.parseInt(st.nextToken()); String name=st.nextToken(); int ratingId=Integer.parseInt(st.nextToken()); 电影x=新电影(id、名称、分级id); 增加(x); } } line++; } br.close(); } catch(FileNotFoundException fnfe){System.out.println(fnfe.getMessage());} catch(IOException io){System.out.println(io.getMessage());} catch(异常e){System.out.println(e.getMessage());} 退货清单; }

读取文本文件并返回ArrayList类型对象的Java方法 publicstaticvoidmain(字符串[]args) { ArrayList LocationsList=readFile(“Locations.csv”,“Locations”); //ArrayList MoviesList=readFile(“Movies.csv”、“Movies”); //ArrayList OperatorList=readFile(“Operators.csv”、“Operators”); //ArrayList PersonCategoryList=readFile(“PersonCategory.csv”,“PersonCategory”); } 公共静态ArrayList读取文件(字符串文件名,字符串whichFile) { ArrayList=新建ArrayList(); 尝试 { BufferedReader br=新的BufferedReader(新文件读取器(文件名)); 字符串indata; 内线=0; 而((indata=br.readLine())!=null) { StringTokenizer st=新的StringTokenizer(indata,“,”); 如果(行!=0) { 如果(whichFile.equals(“位置”)) { int id=Integer.parseInt(st.nextToken()); 字符串city=st.nextToken(); 如果(city.charAt(0)='“') { 字符串c=st.nextToken(); city=city.substring(1,city.length())+“,”+c.substring(0,c.length()-1); } int stateId=Integer.parseInt(st.nextToken()); 地点x=新地点(id、城市、州id); 增加(x); } else if(whichFile.equals(“电影”)) { int id=Integer.parseInt(st.nextToken()); String name=st.nextToken(); int ratingId=Integer.parseInt(st.nextToken()); 电影x=新电影(id、名称、分级id); 增加(x); } } line++; } br.close(); } catch(FileNotFoundException fnfe){System.out.println(fnfe.getMessage());} catch(IOException io){System.out.println(io.getMessage());} catch(异常e){System.out.println(e.getMessage());} 退货清单; },java,Java,我正在尝试创建一个方法,该方法将读取一个文本文件,并可以返回一个ArrayList类型的对象以供多个类使用 但是,也有类似的警告: “类型为ArrayList的表达式需要未经检查的转换才能符合ArrayList” 如何解决此问题?您需要基于ArrayList创建适当的泛型,例如:new ArrayList() 您可以通过向readFile传递一个类来解决此问题,如下所示: public static void main(String[] args) { Array

我正在尝试创建一个方法,该方法将读取一个文本文件,并可以返回一个ArrayList类型的对象以供多个类使用

但是,也有类似的警告: “类型为
ArrayList
的表达式需要未经检查的转换才能符合
ArrayList


如何解决此问题?

您需要基于
ArrayList
创建适当的泛型,例如:
new ArrayList()

您可以通过向readFile传递一个类来解决此问题,如下所示:

    public static void main(String[] args)
    {
        ArrayList <Locations>       LocationsList       = readFile("Locations.csv", "Locations");
        //ArrayList <Movies>          MoviesList          = readFile("Movies.csv", "Movies");
        //ArrayList <Operators>       OperatorsList       = readFile("Operators.csv", "Operators");
        //ArrayList <PersonCategory>  PersonCategoryList  = readFile("PersonCategory.csv", "PersonCategory");
    }
    
    public static ArrayList readFile(String fileName, String whichFile)
    {
        ArrayList list = new ArrayList();

        try
        {
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            
            String indata;
            
            int line = 0;
            while((indata=br.readLine())!=null)
            {
                StringTokenizer st = new StringTokenizer(indata,",");
                
                if(line != 0)
                {
                    if(whichFile.equals("Locations"))
                    {
                        int id = Integer.parseInt(st.nextToken());
                        String city = st.nextToken();
                        if(city.charAt(0) == '"')
                        {
                            String c = st.nextToken();
                            city = city.substring(1,city.length()) +"," +c.substring(0,c.length()-1);
                        }
                        int stateId = Integer.parseInt(st.nextToken());
                        
                        Locations x = new Locations(id, city, stateId);
                        list.add(x);
                    }
                    
                    else if(whichFile.equals("Movies"))
                    {
                        int id = Integer.parseInt(st.nextToken());
                        String name = st.nextToken();
                        int ratingId = Integer.parseInt(st.nextToken());
                        
                        Movies x = new Movies(id, name, ratingId);
                        list.add(x);
                    }                              
                }
                
                line++;
            }
            
            br.close();
        }
        catch (FileNotFoundException fnfe){System.out.println(fnfe.getMessage());}
        catch (IOException io){System.out.println(io.getMessage());}
        catch (Exception e){System.out.println(e.getMessage());}
        
        return list;
    }
publicstaticarraylistreadfile(…..,Class clazz)
{
ArrayList=新建ArrayList();
...
}

本质上,您需要为泛型类指定类型参数
ArrayList

由于要将从不同类创建的对象添加到同一列表中,因此可以创建一个接口,例如,
MyInterface

公共接口MyInterface{
....
}
readFile
返回的所有类都必须实现此接口

公共类电影实现MyInterface{
....
}
现在,您可以在适当的位置添加类型参数
MyInterface

publicstaticvoidmain(字符串[]args){
ArrayList LocationsList=readFile(“Locations.csv”,“Locations”);
....
}
公共静态ArrayList读取文件(字符串文件名,字符串whichFile){
ArrayList=新建ArrayList();
....
}
根据回复添加以下信息

实际上,您可能会选择将接口留空,但随后必须显式地将对象强制转换为具体类才能执行任何有用的操作

  • 您可以在需要时投射每个对象
  • 也可以为每种具体类型编写一个列表转换器函数
  • 公共类ListConverter{
    公共ArrayList ToLocationArrayList(ArrayList inList){
    ArrayList outList=新的ArrayList();
    对于(MyInterface listItem:inList){
    添加((位置)列表项);
    }
    返回最长时间;
    }
    }
    
    然后

    public class ListConverter {
      public ArrayList<Locations> toLocationsArraylist(ArrayList<MyInterface> inList) {
          ArrayList<Locations> outList = new ArrayList<>();
          for (MyInterface listItem : inList) {
              outList.add((Locations) listItem);
          }
          return outList;
      }
    }
    
    publicstaticvoidmain(字符串[]args){
    ArrayList myInterfaceList=readFile(“Locations.csv”,“Locations”);
    ArrayList locationList=ListConverter.ToLocationArrayList(myInterfaceList);
    }
    

    如果您考虑使用此解决方案,则考虑更佳地重命名MyDe界面,例如,<代码> CVScript记录> />代码,或任何特定于域的内容。

    尝试此。

    public static void main(String[] args) {
            ArrayList<MyInterface> myInterfaceList = readFile("Locations.csv", "Locations");
            ArrayList<Locations> locationList = ListConverter.toLocationsArraylist(myInterfaceList);
           
        }
    
    并将它们结合起来

    static Locations convertLocations(String[] fields) {
        int id = Integer.parseInt(fields[0]);
        String city = fields[1];
        if (city.charAt(0) == '"') {
            String c = fields[2];
            city = city.substring(1, city.length()) + "," + c.substring(0, c.length() - 1);
        }
        int stateId = Integer.parseInt(fields[3]);
        Locations x = new Locations(id, city, stateId);
        return x;
    }
    
    static Movies convertMovies(String[] fields) {
        /* Make Movies object from fields */
    }
    
    arraylistlocationslist=readFile(“Locations.csv”,fields->convertLocations(fields));
    ArrayList MoviesList=readFile(“Movies.csv”,fields->convertMovies(fields));
    
    这是我从@saka1029中提取的最后一个代码,并进行了一些调整,以便它能够读取文件中除第一行之外的每一行

    ArrayList<Locations> LocationsList = readFile("Locations.csv", fields -> convertLocations(fields));
    ArrayList<Movies> MoviesList = readFile("Movies.csv", fields -> convertMovies(fields));
    

    使用泛型而不是将类名作为字符串传递,您可以将其作为类类型传递,并使方法泛型兼容这是一个家庭作业吗?
    文件
    类已经有了一个用于此的方法。我已经完成了上面显示的操作。但是有一行错误代码是“方法添加(T)”在类型中,ArrayList不适用于
    列表上的“参数(位置)”。添加(x);
    。如何解决此问题?您的想法看起来不错,但实际上我有10个类需要在
    readFile
    方法上使用。那么,我还需要创建10个conver吗
    public static void main(String[] args) {
            ArrayList<MyInterface> myInterfaceList = readFile("Locations.csv", "Locations");
            ArrayList<Locations> locationList = ListConverter.toLocationsArraylist(myInterfaceList);
           
        }
    
    public static <T> ArrayList<T> readFile(String fileName, Function<String[], T> converter) throws IOException {
        ArrayList<T> result = new ArrayList<>();
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {
            String line = reader.readLine();
            String[] fields = line.split(",");
            T object = converter.apply(fields);
            result.add(object);
        }
        return result;
    }
    
    static Locations convertLocations(String[] fields) {
        int id = Integer.parseInt(fields[0]);
        String city = fields[1];
        if (city.charAt(0) == '"') {
            String c = fields[2];
            city = city.substring(1, city.length()) + "," + c.substring(0, c.length() - 1);
        }
        int stateId = Integer.parseInt(fields[3]);
        Locations x = new Locations(id, city, stateId);
        return x;
    }
    
    static Movies convertMovies(String[] fields) {
        /* Make Movies object from fields */
    }
    
    ArrayList<Locations> LocationsList = readFile("Locations.csv", fields -> convertLocations(fields));
    ArrayList<Movies> MoviesList = readFile("Movies.csv", fields -> convertMovies(fields));
    
        public static <T> ArrayList<T> readFile(String fileName, Function<String[], T> converter)
        {
            ArrayList <T> list = new ArrayList<>();
    
            try
            {
                BufferedReader br = new BufferedReader(new FileReader(fileName));
                br.readLine();
                
                String inData;
                
                while((inData=br.readLine()) != null)
                {
                    String[] fields = inData.split(",");
                    T object = converter.apply(fields);
                    list.add(object);
                }
                
                br.close();
            }
            catch (FileNotFoundException fnfe){System.out.println(fnfe.getMessage());}
            catch (IOException io){System.out.println(io.getMessage());}
            catch (Exception e){System.out.println(e.getMessage());}
            
            return list;
        }
    
        static Locations convertLocations(String[] fields)
        {
            int id = Integer.parseInt(fields[0]);
            String city = fields[1];
            int stateId;
            if (city.charAt(0) == '"')
            {
                String c = fields[2];
                city = city.substring(1, city.length()) + "," + c.substring(0, c.length() - 1);
                stateId = Integer.parseInt(fields[3]);
            }
            else
                stateId = Integer.parseInt(fields[2]);
            
            Locations x = new Locations(id, city, stateId);
            
            return x;
        }