I\'m writing an algorithm where I look for pairs of values which when added together results in another value I\'m looking for.
I figured out that using a Map
HashSet seems to be faster:
Also note that .contains() normally does not need to be called on HashMap and HashSet, but I kept it on the code to more accurately answer your question:
long t = System.currentTimeMillis();
HashMap map = new HashMap<>();
for (int i = 0; i < 10000; i++) {
String s = (Math.random() * 100) + "";
if (!map.containsKey(s)) {
map.put(s, true);
}
}
System.out.println("HashMap: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
ArrayList list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
String s = (Math.random() * 100) + "";
if (!list.contains(s)) {
list.add(s);
}
}
System.out.println("ArrayList: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
HashSet set = new HashSet<>();
for (int i = 0; i < 10000; i++) {
String s = (Math.random() * 100) + "";
if (!set.contains(s)) {
set.add(s);
}
}
System.out.println("HashSet: " + (System.currentTimeMillis() - t));