2015-11-03 71 views
-1

我需要将CSV文件的每一行转换为分离的堆栈(每行一个堆栈)。我的问题是在我扫描每行并将CSV转换为堆栈之后,我应该在哪里存储堆栈?我不知道我要创建多少堆栈,所以我需要一个动态数据结构来存储创建的堆栈。以下是我的代码。我可以将堆栈添加到ArrayList(或链接列表)吗?

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>(); 
      } 
+0

你问是选择一个'ArrayList'还是'LinkedList'?或者你问一般来说是否可以有一个堆栈列表? – RealSkeptic

+1

你为什么不试试?是什么让你觉得你不能将堆栈存储到列表中? –

+3

'List > stackList = new ArrayList >()'是你似乎在寻找的东西。 – ritratt

回答

-1

请指定您的语言以及您正在使用的库。 但是缩进代码更重要。 这就是我以为你在反正以后:

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

我可以告诉没有必要为具有不可过大文件,如超过50 MB,当至少一个“动态数据结构”。

+0

但是,我需要将st值存储到另一个地方(或类)供以后使用。 –

+0

然后你可以使用你的st来完成这些代码。 –

0

这是你正在寻找的实现:

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

但是,不建议,这是有可能通过简单的谷歌搜索或一点基本的研究来解决这些问题的平台。

相关问题