2013-03-26 77 views
-1

這是我到目前爲止有:的Java:堆棧 - > ArrayList的

System.out.println("\fStack - ArrayList Demo\n"); 

     ArrayList<String> al = new ArrayList<String>(); 
     Stack<String> st = new Stack<String>(); 

     // Start with a few elements to the ArrayList 
     al.add("A"); 
     al.add("B"); 
     al.add("C"); 

     st.addAll(al); // Retrieve ArrayList elements for the stack and add them there 
     al.clear(); // Clear arraylist for storage later 


     // Pop out the last element in the stack. 
     System.out.println("\nPop out the last element: "+al.add(st.pop())); 
     System.out.println("What's left of the stack: "+st+"\n"); 
     System.out.println("ArrayList, now: "+al); 

     // Keep popping.. 
     int count = st.search("A"); 
     while (count != -1 && count >= 1) { 
      System.out.println("Popping next.."+al.add(st.pop())); 
      count--; 
     } 

     // Is the Stack empty? 
     System.out.println("\nStack Empty? "+st.empty()); 
     System.out.println("ArrayList now: "+al); 

使用al.add(st.pop()));返回 「真」,當我運行程序。有沒有辦法讓它產生被彈出的實際元素(A,B,C)?

+1

String element = st.pop(); System.out.println(「element is」+ element); al.add(element); – 2013-03-26 21:28:41

+1

String elm = st.pop(); al.add(ELM); ? – kufudo 2013-03-26 21:30:10

+1

@RonDahlgren:和kufudo:你可以用反引號標註代碼中的代碼:' – jlordo 2013-03-26 21:32:41

回答

0

javadoc用於補充指出:

Returns: 
true (as specified by Collection.add(E)) 

這聽起來像你想打印您要添加的元素。所以:

String elem = st.pop(); 
    System.out.println("adding " +elem); 
    al.add(elem) 

如果您打算成爲一名軟件開發人員,閱讀和理解文檔是一種寶貴的實踐技能。