In the following test:
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("start 1: " + new Date());
Collection collection = new ArrayList();
for (int i = 0; i < 1000 * 1000 * 1000; i++) {
collection.add(new Object());
}
System.out.println("middle 1: " + new Date());
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
iterator.next().toString();
}
System.out.println("\nend 1: " + new Date());
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("start 2: " + new Date());
Collection collection = new HashSet();
for (int i = 0; i < 1000 * 1000 * 1000; i++) {
collection.add(new Object());
}
System.out.println("middle 2: " + new Date());
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
iterator.next().toString();
}
System.out.println("\nend 2: " + new Date());
}
});
t1.start();
t2.start();
}
I got an OutOfMemory for the ArrayList approach.
But, on this high voted answer, it says HashSet consumes more memory. The broken link on the answer looks like to be this one.
Is there something wrong with my test? Or ArrayLists are, really, worst for memory usage than HashSet?
--update: actually, by using collection.add("."); I get the outOfMemory from the arrayList. But for collection.add(new Object()); I get for both.