1

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.

Alpe89
  • 299
  • 2
  • 11
  • 1
    Replace `al.remove(next); i = al.iterator();` with `i.remove();`. – shmosel Nov 22 '17 at 07:55
  • Learn Data Structure. underline data structure they use either `Array` or `linked nodes` then you should be able to understand not only lists, but sets, stacks, heaps, queues etc..so on – Luminous_Dev Nov 22 '17 at 07:56

2 Answers2

2

but I want to know if there is a better alternative

Yes.

because I don't really know what can be in a specific position in an ArrayList (they contains objects of every kind.

  1. Make List<T> generic : it will allow you to add only some specific type of Object.

  2. Replaced ArrayList al = new ArrayList(); by List<String> al = new ArrayList<>();

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
2

You don't need to fetch each element before you remove it. You can simply remove elements by it's index:

ArrayList al = new ArrayList();

// ... add elements skipped...

// now clear it 
int size = al.size();
for (int index = size-1; index >= 0; index--) {
    al.remove(index);
}
Marc
  • 1,900
  • 14
  • 22
  • 1
    One good thing about this code that is worth mentioning is that it removes from the end towards the start. For ArrayList, this is much more efficient than removing from the beginning. It avoids shifting the elements of the array every time you remove an element. – DodgyCodeException Nov 22 '17 at 07:58
  • That's funny because my first idea was to use a simple for loop and remove every element, but then I realized that ArrayLists are resized at every insert/remove action. Obviously if you go backwards that's not a problem, thank you! – Alpe89 Nov 22 '17 at 08:00