【问题标题】:Accessing Elements in an ArrayList of ArrayLists访问 ArrayList 的 ArrayList 中的元素
【发布时间】:2020-06-26 23:26:43
【问题描述】:

我有一个 ArrayList 的 ArrayList,我正在尝试访问其中的元素,并且通常添加、删除、替换和获取项目。

我的代码如下。

import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
 

public class MarvelNetworkRearrange {
    public static void main(String[] args) {
        
        BufferedReader csvReader = null;
        
        try {
            String newLine;
         ArrayList B = new ArrayList<ArrayList>();
            csvReader = new BufferedReader(new FileReader("MARVEL P2P.csv"));
         Integer i = 0;
            

            while ((newLine = csvReader.readLine()) != null) 
         {
            B.add(A(newLine));
            }
         File f = new File("MarvelRearranged.csv");
         PrintWriter printWriter = new PrintWriter(f);
         
         ArrayList<String> x = new ArrayList<String>();
         x = B.get(0);
         x.remove(0);
         
         System.out.println(x);
         
         
        } 
      catch (IOException e) 
      {
            e.printStackTrace();
        } 
      finally 
      {
            try 
         {
                if (csvReader != null) csvReader.close();
            } 
         catch (IOException newException) 
         {
                newException.printStackTrace();
            }
        }
    }
    public static ArrayList<String> A(String fromCSV) {
        ArrayList<String> csvResult = new ArrayList<String>();
        
        if (fromCSV != null) 
      {
            String[] splitData = fromCSV.split("\\s*,\\s*");
            for (int i = 0; i < splitData.length; i++) 
         {
                if (!(splitData[i] == null) || !(splitData[i].length() == 0)) 
            {
                    csvResult.add(splitData[i].trim());
                }
            }
        }
        return csvResult;
    }
}

我正在读取 .csv 文件,并尝试重新排列 .csv 文件中的项目,以便创建一个可以更有效地用于项目的 .csv 文件。但是,当我运行此代码时,在“x = B.get(0);”处出现“错误:不兼容的类型:对象无法转换为 ArrayList”。我也试过 x.get(0).remove(0)。

我试图删除 ArrayList B 中第一个 ArrayList 的第一个元素,那么我做错了什么?我试图删除它的原因是指定的元素是 .csv 中的一个空格(在创建原始文件时故意这样做,因为它是矩阵中标题之间的空间)。

请帮忙!

【问题讨论】:

  • 我认为您应该包含一个 .csv 文件的小样本。
  • 我认为你应该用new ArrayList&lt;ArrayList&lt;String&gt;&gt;();替换new ArrayList&lt;ArrayList&gt;();

标签: java arraylist printwriter


【解决方案1】:

你定义了你的ArrayList B 没有类型,但是ArrayList xString 类型。您需要转换类型,或者您需要遵循以下更好的方法:

指定ArrayList B的类型:

ArrayList<ArrayList<String>> B = new ArrayList<>();

要从ArrayList 中删除任何元素,请跳过创建另一个对象并指向B 的元素,直接从B 中删除:

B.get(0).remove(0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 2015-06-07
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    相关资源
    最近更新 更多