简体   繁体   中英

Stats of HashSet

I wonder if there is a best way to get the aggregated statistics of objects in a HashSet . Is there any good approach rather than iterating the whole Set ?

import java.lang.Thread.State;
import java.util.HashSet;
import java.util.Set;

public class Stats {

    static class Item {

        private State state;

        public State getState() {
            return state;
        }

        public void setState(State state) {
            this.state = state;
        }

        public Item(State state){
            this.state = state;
        }
    }

    public static void main(String[] args) {

        Set<Item> items = new HashSet<Stats.Item>();
        items.add(new Item(State.NEW));
        items.add(new Item(State.BLOCKED));
        items.add(new Item(State.BLOCKED));

        /*
         * printout here
         */
            // New=1
            // Blocked=2
    }
}

No,but you can write your own implementation of Set interface and in add method check item state and increments counters. Then you can retrive stats.

No their isn't. However with a self-made implementation or a wrapper you might be able to calculate statistics while inserting into the hash set.

If memory serves, doing something like this with a Set implementation is presented as an example in Bloch's Effective Java. Chosen precisely because if you want stats on the collection, you have to roll your own.

A search here reveals the reference I am thinking of, where he discusses composition over inheritance: How is having a wrapper class equals composition as described Joshua Bloch?

I admit this is not strictly an answer to the question, but I think it adds to the conversation and shows an example of how (and why) to make your own instrumented classes for your own purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM