wassup
wassup

Reputation: 2503

Creating a collection with single object per class

Is there, in Java, a collection that can be used to store unique-class objects?

For example, I have one parent class (Parent) and several child classes (ChildA, ChildB, and so on) that inherit directly from Parent.

Now, I need to store each class' instance in a collection (Collection<Parent>). When I add ChildA to the collection once, I must not be able add more ChildA's.

I'd like to be able to retrieve each instance by calling get(ClassB.class), and remove it in a similiar manner.

Does there already exist a collection providing that functionality, or do I have to write my own implementation?

Upvotes: 1

Views: 271

Answers (2)

JB Nizet
JB Nizet

Reputation: 691765

Write your own class that uses a Map<Class<? extends Parent>, Parent>:

private Map<Class<? extends Parent>, Parent> map = new HashMap<>();

public void add(Parent p) {
    if (!map.containsKey(p.getClass()) {
        map.put(p.getClass(), p);
    }
}

public Parent get(Class<? extends Parent> clazz) {
    return map.get(clazz);
}

Upvotes: 3

akkerman
akkerman

Reputation: 119

please have a look at HashSet http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

Upvotes: -1

Related Questions