Which Java collection allows fastest element removal?

john :

I'm looking for a collection that allows fastest element removal. I tested ArrayList on 1 million rows and it turns out removing the first element is faster than removing the last one. It takes about 50 seconds to remove one million elements

import java.util.ArrayList;

public class TestArray {

    final int numberOfElements = 1000000; 

    public void testArray () { 

    // test array 
    ArrayList<String> testArray = new ArrayList<String>(); 
    for (int i = 0; i < numberOfElements; i++) { 
        testArray.add("" + Math.random()); 
    }

    // testing speed when removing the first element  
    long startTime = System.currentTimeMillis(); 
    while (true) { 
        if (testArray.isEmpty()) { 
            System.out.println("Milliseconds to fisnish when removing the first element " + (System.currentTimeMillis() - startTime));
            break; 
        } 
        else { 
            String testString = testArray.get(0); 
            testArray.remove(testString); 
        }
    } 

    testArray = new ArrayList<String>(); 
    for (int i = 0; i < numberOfElements; i++) { 
        testArray.add("" + Math.random()); 
    } 
    // testing speed when removing the last   element  
        long startTime2 = System.currentTimeMillis(); 
        while (true) { 
            if (testArray.isEmpty()) { 
                System.out.println("Milliseconds to fisnish when removing the last element " + (System.currentTimeMillis() - startTime2));
                break; 
            } 
            else { 
                String testString = testArray.get(testArray.size()-1); 
                testArray.remove(testString); 
            }
        }



    } 

}

But I'm not sure if this is the fastest possible way. Is 50 seconds the fastest way? Or is there any better collection, for example will LinkedList do it faster? Or what is the fastest collection to remove elements one by one?

RLM :

1) You should consider LinkedList which has O(1) Big O performance for remove operation (Explanation below), while ArrayList is O(n).
2) You can try HashSet if you are not interested in duplicates.

LinkedList Remove:

1) LinkedList removal at the beginning and end is constant time since traversal is not required.

2) It takes longer time for removing the middle elements because the element needs to be found first.

3) If you have an iterator at the location you want to remove, then remove is constant time.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113258&siteId=1