I'm currently learning Java, I'm just curious about the code that I wrote a minute ago, it works, but I want to know if there is a better alternative (that isn't "use the clear method").
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("A");
al.add("B");
al.add(5);
System.out.println(al.size());
Iterator i = al.iterator();
while (i.hasNext()) {
Object next = i.next();
System.out.println("Removing " + next.toString() + "...");
al.remove(next);
i = al.iterator();
}
System.out.println(al.size());
}
Especially, because I don't really know what can be in a specific position in an ArrayList (they contains objects of every kind), I used a generic "Object next" variable. I don't know if it is acceptable.
I know that there are methods to clear an ArrayList, I just wanted to try to understand how ArrayLists works, thank you.