簡體   English   中英

Java 方法讀取文本文件並返回 ArrayList 類型 object

[英]Java method to read text file and return ArrayList type object

    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;
    }

我正在嘗試創建一種方法,該方法將讀取文本文件並可以返回 ArrayList 類型 object 以使用多個 Class。 使用我上面的代碼,它可以成功運行。

但是,有如下警告行:“ ArrayList類型的表達式需要未經檢查的轉換以符合ArrayList<Locations>

我該如何解決?

嘗試這個。

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;
}

並定義將 CSV 線轉換為 object 的轉換器。

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));

您需要使用例如創建正確的基於泛型的ArrayListnew ArrayList<Location>()

您可以通過將 class 傳遞給 readFile 來解決此問題,如下所示:

public static <T> ArrayList<T> readFile(....., Class<T> clazz)
{
   ArrayList<T> list = new ArrayList<T>();
   ...
}

本質上,您需要為通用 class ArrayList指定類型參數。

由於您將從不同類創建的對象添加到同一個列表中,因此您可以創建一個接口,例如MyInterface

public interface MyInterface {
    ....
}

readFile返回的所有類都必須實現此接口。 例如。

public class Movies implements MyInterface {
    ....
}

現在,您可以在適當的位置添加類型參數MyInterface

public static void main(String[] args) {
        ArrayList<MyInterface> LocationsList = readFile("Locations.csv", "Locations");
        ....
    }

public static ArrayList<MyInterface> readFile(String fileName, String whichFile) {
 
  ArrayList<MyInterface> list = new ArrayList<>();
            ....
        }

根據回復添加以下信息

實際上,您可能選擇將接口留空,但是您必須將對象顯式轉換為具體類才能做任何有用的事情。

  1. 您可以在需要時投射每個 object
        MyInterface myInterfaceObject = locationsList.get(0)
        Locations locations = Locations.class.cast(myInterfaceObject);

或者

        MyInterface myInterfaceObject = locationsList.get(0)
        Locations locations = (Locations) myInterfaceObject;
  1. 或者您可以為每種具體類型編寫一個列表轉換器 function
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;
  }
}

接着

public static void main(String[] args) {
        ArrayList<MyInterface> myInterfaceList = readFile("Locations.csv", "Locations");
        ArrayList<Locations> locationList = ListConverter.toLocationsArraylist(myInterfaceList);
       
    }

如果您確實考慮使用此解決方案,請考慮更適當地重命名 MyInterface ,例如,重命名為CsvRecord或任何特定於域的名稱。

這是我從@saka1029 獲取的最終代碼並進行了一些調整,以便它可以讀取文件中除第一行之外的每一行。

    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;
    }

這是我對 @saka1029 答案中convertLocations方法的更正版本。

    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;
    }

Java 方法添加 ArrayList 未定義類型<object><div id="text_translate"><p>我正在為我的作業構建一個 java 程序,我必須將產品添加到特定商店。 嘗試從 Store class 添加到 ArrayList 時遇到問題。</p><p> 我有 class 產品如下:</p><pre> class Product { private String pName; private int pPrice; private int pQty; public Product (String pName, int pPrice, int pQty) { this.pName = pName; this.pPrice = pPrice; this.pQty = pQty; } }</pre><p> class 存儲如下:</p><pre> class Store { private String storeName; ArrayList&lt;Product&gt; pList =new ArrayList&lt;&gt;(); public Store() { String name = storeName; pList = new ArrayList&lt;Product&gt;(); } public Store(String newStoreName,ArrayList&lt;Product&gt; newPList) { this.storeName = newStoreName; this.pList = newPList; } void setName(String storeName) { this.storeName = storeName; } void setProduct(Product pList) { pList.add(this.pList);//This return method add undefined for type Product, how to solve this error? } String getName() { return storeName; } ArrayList&lt;Product&gt; getProductList() { return pList; } }</pre></div></object>

[英]Java Method add ArrayList is undefined for the type <OBJECT>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 讀取文本文件並將其添加到Java中的對象的ArrayList中 從文本文件讀取,然后以私有方法返回到arraylist Java將文件讀入對象的數組列表並返回該數組列表 如何讀取JAR文件中的方法正在返回的對象類型的數組列表 如何在Java中將文本文件讀取到不同對象類型的ArrayList? Java 方法添加 ArrayList 未定義類型<object><div id="text_translate"><p>我正在為我的作業構建一個 java 程序,我必須將產品添加到特定商店。 嘗試從 Store class 添加到 ArrayList 時遇到問題。</p><p> 我有 class 產品如下:</p><pre> class Product { private String pName; private int pPrice; private int pQty; public Product (String pName, int pPrice, int pQty) { this.pName = pName; this.pPrice = pPrice; this.pQty = pQty; } }</pre><p> class 存儲如下:</p><pre> class Store { private String storeName; ArrayList&lt;Product&gt; pList =new ArrayList&lt;&gt;(); public Store() { String name = storeName; pList = new ArrayList&lt;Product&gt;(); } public Store(String newStoreName,ArrayList&lt;Product&gt; newPList) { this.storeName = newStoreName; this.pList = newPList; } void setName(String storeName) { this.storeName = storeName; } void setProduct(Product pList) { pList.add(this.pList);//This return method add undefined for type Product, how to solve this error? } String getName() { return storeName; } ArrayList&lt;Product&gt; getProductList() { return pList; } }</pre></div></object> 傳遞一個ArrayList <Object> 作為方法的參數,處理arrayList並將其返回-Java 如何從Java中的文本文件讀取ArrayList? Java-讀取文本文件,將內容存儲在ArrayList中,打印ArrayList Java 按類型返回 ArrayList
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM