So I am working on the question of the best way of finding the two most common elements in an array list.
My method is to turn the whole thing to a hashmap, then see which one is the greatest. Because I like hashmaps. They seemed like a good way to do it and I wasn't able to come up with a better solution.
Except that I am getting an error. Which is where you come in (= !
public static String[] findTwo(ArrayList<String> param) {
Map<String, Integer> counter = new HashMap<String, Integer>();
for (int i = 0; i < param.size(); i++) {
//param.get(i) is name of inserted object
if (counter.get(i) == null) {
counter.put(param.get(i), 1);
System.out.println(counter.get(i) + "<-- should be 1"); // <-- erroneous part!
} else {
counter.put(param.get(i), counter.get(i)+1);
System.out.println("elsing");
}
System.out.println(counter);
}
return null;
}
This code prints
null<-- should be 1
{HIHI=1}
null<-- should be 1
{HIHI=1}
null<-- should be 1
{HIHI=1}
null<-- should be 1
{HIHI=1}
null<-- should be 1
{yoyo=1, HIHI=1}
null<-- should be 1
{yoyo=1, HIHI=1}
null<-- should be 1
{yoyo=1, nono=1, HIHI=1}
null<-- should be 1
{yoyo=1, nono=1, froyo=1, HIHI=1}
Which is completely wrong!
It is saying that the value is null after I insert a 1. I am not sure why that is? =(
Ahhh thank you all!
Can anyone help me figure out what the time cost is?