Search code examples
javatypessettype-safety

How to create a Set in which only a single type can be added which doesn't permit subclasses or superclasses to be added?


I want a Set which only holds one data type and doesn't permit any of its superclasses or subclasses from being added to the Set.


Solution

  • you can use Object.getClass() do determine the type of your objects.

    if you want a guarantuee that only classes of a type MyClass are added you could just extend HashSet and override the add(Object o) method and only add the element to the collection if (o.getClass() == MyClass.class):

    Update: added a working example that you can run as PoC.

    public class MySet extends HashSet<MySet.MyClass> {
        public static class MyClass {}
    
        public static class MySubClass extends MyClass {}
    
        @Override
        public boolean add(MyClass c) {
            if (c.getClass() != MyClass.class) {
                throw new IllegalArgumentException("illegal class to add " + c.getClass().getName());
            }
            return super.add(c);
        }
    
        public static void main(String[] args) {
            MySet set = new MySet();
            set.add(new MyClass());   // works
            set.add(new MySubClass()); // throws Exception
        }
    
    }
    

    running this example yields:

    Exception in thread "main" java.lang.IllegalArgumentException: illegal class to add MySet$MySubClass