Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of references to certain type in ArrayList

Tags:

java

arraylist

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?

like image 358
JustAnotherDoomer Avatar asked Dec 04 '25 03:12

JustAnotherDoomer


2 Answers

You can use the getClass() method to determine some object's class.

Take a look at the documentation for Object.

like image 117
Hazim Avatar answered Dec 05 '25 19:12

Hazim


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.

like image 44
Farruh Habibullaev Avatar answered Dec 05 '25 20:12

Farruh Habibullaev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!