2015-09-13 23 views
5

Tôi mới sử dụng Java Bộ sưu tập và sự nghi ngờ của tôi là lý do tại sao tôi không thể đi qua một phần tử trong danh sách liên kết theo hướng ngược lại.Tôi sẽ giải thích những gì tôi đã làm và làm rõ những nghi ngờ của tôi.Làm thế nào để lặp lại một phần tử LinkedList theo thứ tự ngược lại?

  1. tôi đã tạo ra giao diện iterator cho lặp về phía trước và listiterator cho lặp lạc hậu. Tại sao lặp lại không hoạt động?
  2. Tôi không thể sử dụng trình lặp sốtrình liệt kê giao diện trong cùng một chương trình để đi qua một tập hợp các phần tử trong lặp lại chuyển tiếp và lùi?

    Đoạn Mã:

    import java.util.*; 
    class NewClass{ 
    public static void main(String args[]){ 
        LinkedList<String> obj = new LinkedList<String>(); 
    
        obj.add("vino"); 
        obj.add("ajith"); 
        obj.add("praveen"); 
        obj.add("naveen"); 
    
        System.out.println(obj); 
    
        System.out.println("For loop "); 
        //using for loop 
        for(int count=0; count < obj.size(); count++){ 
        System.out.println(obj.get(count)); 
        } 
        System.out.println("For each loop "); 
    
        //using foreach loop 
        for(String s:obj){ 
        System.out.println(s); 
        } 
        System.out.println("Whileloop "); 
    
        //using whileloop 
        int count=0; 
        while(obj.size() > count){ 
         System.out.println(obj.get(count)); 
        count++; 
        } 
        System.out.println("Forward Iterations "); 
        //using iterator 
        Iterator it = obj.iterator(); 
        while(it.hasNext()){ 
        System.out.println(it.next()); 
        } 
        ListIterator lit = obj.listIterator(); 
        System.out.println("Backward Iterations"); 
        while(lit.hasPrevious()){ 
        System.out.println(lit.previous()); 
         } 
        } 
    } 
    

    Output

    [vino, ajith, praveen, naveen] 
    For loop 
    vino 
    ajith 
    praveen 
    naveen 
    For each loop 
    vino 
    ajith 
    praveen 
    naveen 
    Whileloop 
    vino 
    ajith 
    praveen 
    naveen 
    Forward Iterations 
    vino 
    ajith 
    praveen 
    naveen 
    Backward Iterations 
    

Đâu là đầu ra cho Iterations ngược? Hãy ai giúp đỡ me.Thanks trước

+0

Bạn có chắc chắn bắt đầu lặp lại từ phần tử danh sách cuối cùng không? –

Trả lời

4

Bạn có thể làm điều đó, nhưng bạn cần phải sử dụng phương pháp listIterator(int index) để xác định rằng bạn muốn bắt đầu ở cuối số List.

LinkedList<String> obj = new LinkedList<String>(); 

obj.add("vino"); 
obj.add("ajith"); 
obj.add("praveen"); 
obj.add("naveen"); 

ListIterator<String> it = obj.listIterator(obj.size()); 
while (it.hasPrevious()) 
    System.out.println(it.previous()); 
Các vấn đề liên quan