Search code examples
javaarraylistcollectionsstringbuffer

print ArrayList that contains StringBuffer objects


I have an ArrayList, that stores objects of StringBuffer class. Now I want to print that ArrayList. How could I do that.

Iterator itr=al.iterator(); 
while(itr.hasNext())
{  
    System.out.println(itr.next()); 
}

This just prints the last object for al.size times. Also if you could please tell me why it only prints the last object's value


Solution

  • public class Test {
    
        public static void main(String[] args) {
    
            ArrayList al = new ArrayList();
            al.add(new StringBuffer("keshav"));
            al.add(new StringBuffer("sharma"));
    
            Iterator itr = al.iterator();
            while (itr.hasNext()) {
                System.out.println(itr.next());
            }
    
        }
    
    }
    

    Its working fine for me.

    output:

    keshav
    sharma