[英]Accessing Elements in an ArrayList of ArrayLists
I have an ArrayList of ArrayLists, and I'm trying to access the elements inside, and generally add, remove, replace, and get the items.我有一个 ArrayLists 的 ArrayList,我正在尝试访问其中的元素,并且通常添加、删除、替换和获取项目。
My code is below.我的代码如下。
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;
}
}
I'm reading in a.csv file, and I'm attempting to rearrange the items in the.csv file in order to create a.csv file that I can use more effectively for a project.我正在阅读 a.csv 文件,我正在尝试重新排列 .csv 文件中的项目,以创建一个我可以更有效地用于项目的.csv 文件。 However, when I run this code, I get "error: incompatible types: Object cannot be converted to ArrayList" at "x = B.get(0);".
但是,当我运行此代码时,在“x = B.get(0);”处出现“错误:不兼容的类型:Object 无法转换为 ArrayList”。 I have also tried x.get(0).remove(0).
我也试过 x.get(0).remove(0)。
I am trying to remove the first element of the first ArrayList in the ArrayList B, so what am I doing wrong?我正在尝试删除 ArrayList B 中第一个 ArrayList 的第一个元素,那么我做错了什么? The reason I'm trying to remove it is that the specified element is a blank space in the.csv (done intentionally when creating the original, as it was the space between the headers in a matrix).
我试图删除它的原因是指定的元素是.csv 中的空格(在创建原始元素时故意这样做,因为它是矩阵中标题之间的空间)。
Please help!请帮忙!
You have defined your ArrayList B
without type, but ArrayList x
has String
type.您已经定义了没有类型的
ArrayList B
,但ArrayList x
具有String
类型。 Either you need to cast the type, or you need to follow below approach which is better:您需要转换类型,或者您需要遵循以下更好的方法:
Specify type of ArrayList B
:指定
ArrayList B
的类型:
ArrayList<ArrayList<String>> B = new ArrayList<>();
To delete any element from your ArrayList
, skip creating another object and point to an element of B
, directly delete from B
:要从
ArrayList
中删除任何元素,请跳过创建另一个 object 并指向B
的元素,直接从B
中删除:
B.get(0).remove(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.