In: Computer Science
The following code is included for the java programming problem:
public class Bunny {
private int bunnyNum;
public Bunny(int i) {
bunnyNum = i;
}
public void hop() {
System.out.println("Bunny " + bunnyNum + " hops");
}
}
Display the following output:
+++++++++++ hop in for-loop
Bunny 0 hops
Bunny 1 hops
Bunny 2 hops
Bunny 3 hops
Bunny 4 hops
----------- hop in Enhanced-loop
Bunny 0 hops
Bunny 1 hops
Bunny 2 hops
Bunny 3 hops
Bunny 4 hops
*********** hop in Iterator style
Bunny 0 hops
Bunny 1 hops
Bunny 2 hops
Bunny 3 hops
Bunny 4 hops
I have implemented the program to iterate the ArrayList using for,enhanced-for and iterator per the given description.
Please find the following Code Screenshot, Output, and Code.
ANY CLARIFICATIONS REQUIRED LEAVE A COMMENT
1.CODE SCREENSHOT :


2.OUTPUT :

3.CODE :
Main.java
import java.util.*;
public class Main{
        public static void main(String args[]){
                //create a array list to store "Bunny" Class object
                ArrayList<Bunny> a=new ArrayList<Bunny>();
                int i;
                //use for loop to store 5 obejcts 
                for(i=0;i<5;i++)
                        a.add(new Bunny(i));
                //use for loop to iterate
                System.out.println("+++++++++++ hop in for-loop");
                for(i=0;i<5;i++)
                        a.get(i).hop();
                //use enhanced for loop to iterate
                System.out.println("----------- hop in Enhanced-loop");
                for (Bunny b:a)
                        b.hop();
                //create a iterator
                 Iterator<Bunny> itr=a.iterator();
                 System.out.println("*********** hop in Iterator style");
                 //iterate using iterator
                while(itr.hasNext())
                        itr.next().hop();
        }
}
Bunny.java
public class Bunny {
       private int bunnyNum;
       public Bunny(int i) {
              bunnyNum = i;
       }
       public void hop() {
              System.out.println("Bunny " + bunnyNum + " hops");
       }
}