- #1
Kat3rina
- 4
- 0
1.Homework Statement +
Hello,
I really need your help, because I'm a Java newbie and I've got stuck in this Java homework.
I should implement class ObjectCounter, which has to include two methods:
Implemented class ObjectCounter has to use the HashMap and all of it has to be called this way:
But it always ends with java.lang.NullPointerException, but I don't know how to repair it.
Thank you very much!
Homework Equations
Hello,
I really need your help, because I'm a Java newbie and I've got stuck in this Java homework.
I should implement class ObjectCounter, which has to include two methods:
Code:
// increase the counter for given object
public void add(Object o)
// returns the current number of objects, i.e. current value of counter
public int getCount(Object o)
Implemented class ObjectCounter has to use the HashMap and all of it has to be called this way:
Code:
ObjectCounter objectCounter = new ObjectCounter();
objectCounter.add("hi");
// has to print 1
System.out.println(objectCounter.getCount("hi"));
// has to print 0
System.out.println(objectCounter.getCount("hello"));
objectCounter.add("hi");
// has to print 2
System.out.println(objectCounter.getCount("hi"));
objectCounter.add("hello");
// has to print 1
System.out.println(objectCounter.getCount("hello"));
The Attempt at a Solution
Code:
public class ObjectCounter {
private HashMap<Integer, Integer> map = new HashMap();
public void add(Object o) {
int counter = getCount(o);
if (counter == 0) {
map.put(o.hashCode(), 1);
} else {
map.remove(o.hashCode());
map.put(o.hashCode(), counter++);
}
}
public int getCount(Object o) {
System.out.println(map.get(o.hashCode()));
return map.get(o.hashCode());
}
}
But it always ends with java.lang.NullPointerException, but I don't know how to repair it.
Thank you very much!