public class adding{
static MyArrayList zoo = new MyArrayList() {
@Override
public Iterator<Object> iterator() {
return null;
}
};
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
String[] zooList = {"Cheetah", "Jaguar", "Leopard", "Lion", "Panther", "Tiger"};
for (String x: zooList) zoo.add(x);
printZoo();
System.out.printf("\nTesting the iterator\n>> ");
Iterator it = zoo.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.printf("\nTesting the iterator again without resetting\n>> ");
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.printf("\nTesting the iterator again after resetting\n>> ");
it = zoo.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.printf("\nTesting for-each loop\n>> ");
for(Object animal: zoo) System.out.print(animal + " ");
System.out.println();
System.out.println("\nLetting all the animals escape");
while (zoo.size()>0) zoo.remove(0);
printZoo();
System.out.printf("\nTesting the iterator with an empty list\n>> ");
it = zoo.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
System.out.println("\nTest complete");
}
}
Right now when I run this it come out with error:OUTPUT
The zoo now holds 6 animals: Cheetah Jaguar Leopard Lion Panther Tiger
Exception
inTesting threadthe "main"iterator
>> Cheetah Jaguar Leopard Lion Panther //Not posting everything in array.
Testing the iterator again without resetting
>> java.lang.NullPointerException
at
Testing adding.main(adding.java:28)the iterator again after resetting
at>> sun.reflect.NativeMethodAccessorImpl.invoke0(NativeCheetah Method)Jaguar Leopard Lion Panther
at
Testing for-each loop
>> Cheetah Jaguar Leopard Lion Panther
Letting all the sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)animals escape
atThe zoo now sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.javaholds 0 animals:43)
at
Testing java.lang.reflect.Method.invoke(Method.java:497)the iterator with an empty list
at>> com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)Tiger
NotPretty sure how to go onthe logic of my iterator from here, appreciate all help as I'm a new Java programmerthe MyArrayList class is not accurate.