Let's say I've made the following.
ArrayList<Object> happylist = new ArrayList<Object>();
happylist.add("cat");
happylist.add(98);
...
And so on, adding different types of elements. What sort of method would help me count how many times there was a reference to certain type in my ArrayList?
You can use the getClass() method to determine some object's class.
Take a look at the documentation for Object.
It could easily be done counting the number of different types of reference in the list using reflections. I have coded the following method:
public Map<String, Integer> countReferences(List<Object> happyList) {
Map<String, Integer> referenceCounter = new HashMap<>();
for (Object object : happyList) {
String className = object.getClass().getName();
referenceCounter.put(className, referenceCounter.getOrDefault(className, 0) + 1);
}
return referenceCounter;
}
Basically, each class with difference name gives difference reference. By counting reference to each type, and storing them in map gives you what you are looking for.
But I am not quite sure the usefulness of such particular problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With