Java 我可以将堆栈添加到ArrayList(或链表)中吗?
我需要将CSV文件的每一行转换为单独的堆栈(每行一个堆栈)。我的问题是在扫描每一行并将CSV转换为堆栈后,我应该将堆栈存储在哪里?我不知道要创建多少堆栈,所以我需要一个动态数据结构来存储创建的堆栈。下面是我的代码Java 我可以将堆栈添加到ArrayList(或链表)中吗?,java,data-structures,stack,Java,Data Structures,Stack,我需要将CSV文件的每一行转换为单独的堆栈(每行一个堆栈)。我的问题是在扫描每一行并将CSV转换为堆栈后,我应该将堆栈存储在哪里?我不知道要创建多少堆栈,所以我需要一个动态数据结构来存储创建的堆栈。下面是我的代码 Scanner scanner = new Scanner(new FileReader(filepath)); Stack<String> st = new Stack<String>(); String line; while (
Scanner scanner = new Scanner(new FileReader(filepath));
Stack<String> st = new Stack<String>();
String line;
while (scanner.hasNextLine()){
line = scanner.nextLine();
List<String> items = Arrays.asList(line.split(":",-1));
String x=items.get(0);
while(x == null || x.equals("#"))
{
line = scanner.nextLine();
items=Arrays.asList(line.split(":",-1));
x=items.get(0);
}`
st.addAll(items);
//i need to store st into a data structure before i clear it.
st = new Stack<String>();
}
Scanner Scanner=new Scanner(new FileReader(filepath));
Stack st=新堆栈();
弦线;
while(scanner.hasNextLine()){
line=scanner.nextLine();
List items=Arrays.asList(line.split(“:”,-1));
字符串x=items.get(0);
while(x==null | | x.equals(“#”)
{
line=scanner.nextLine();
items=Arrays.asList(line.split(“:”,-1));
x=项目。获取(0);
}`
st.addAll(项目);
//在清除st之前,我需要将其存储到数据结构中。
st=新堆栈();
}
请指定您的语言以及使用的库。
然而,正确缩进代码更为重要。
这就是我认为你想要的:
Scanner scanner = new Scanner(new FileReader(filepath));
List<Stack<String>> st = new List<Stack<String>>();
String line;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
List<String> items = Arrays.asList(line.split(":",-1));
String x = items.get(0);
if (x != null && !x.equals("#"))
st.add(items);
}
Scanner Scanner=new Scanner(new FileReader(filepath));
List st=新列表();
弦线;
while(scanner.hasNextLine())
{
line=scanner.nextLine();
List items=Arrays.asList(line.split(“:”,-1));
字符串x=items.get(0);
如果(x!=null&&!x.equals(“#”)
st.add(项目);
}
我能说的是,至少在没有过大的文件(如超过50 Mb)时,不需要“动态数据结构”。这是您正在寻找的实现:
String line;
while (scanner.hasNextLine()){
line = scanner.nextLine();
List<String> items = Arrays.asList(line.split(":",-1));
String x=items.get(0);
while(x == null || x.equals("#"))
{
line = scanner.nextLine();
items=Arrays.asList(line.split(":",-1));
x=items.get(0);
}`
st.addAll(items);
stackList.add(st);
//i need to store st into a data structure before i clear it.
st = new Stack<String>();
}
字符串行;
while(scanner.hasNextLine()){
line=scanner.nextLine();
List items=Arrays.asList(line.split(“:”,-1));
字符串x=items.get(0);
while(x==null | | x.equals(“#”)
{
line=scanner.nextLine();
items=Arrays.asList(line.split(“:”,-1));
x=项目。获取(0);
}`
st.addAll(项目);
堆栈列表。添加(st);
//在清除st之前,我需要将其存储到数据结构中。
st=新堆栈();
}
但是,不建议将此作为解决此类问题的平台,而这些问题可能通过简单的谷歌搜索或一点基础研究来解决。您是在询问是选择
ArrayList
还是LinkedList
?或者你是在问是否可以有一个总体堆栈列表?为什么不试试?什么使您认为无法将堆栈存储到列表中?List stackList=new ArrayList()
似乎是您要查找的。但是,我需要将st值存储到另一个位置(或类)以供以后使用。然后,您可以在这些代码行之后使用st来执行此操作。