Search code examples
javagenericscompile-timetype-safety

Is there any way to ensure type safety in java at compile time without generics


I am writing a java application using older version of java SDK which doesn't support Generics. So, How can I assure type safety during compile time. I can use instanceof(). But, it does ensure run time type safety. Please provide your suggestions.


Solution

  • In the bad old days, collections and maps were typically stuffed inside a class whose methods expose the right types. So, to create a "typesafe" list of integers, you might do something like:

    class IntegerList {
        private final List delegate = new ArrayList();
    
        public boolean add(Integer i) {
            return delegate.add(i);
        }
    
        public Integer get(int index) {
            return (Integer) delegate.get(i);
        }
    
        public Iterator iterator() {
            return delegate.iterator();
        }
    
        // etc
    }
    

    Of course, you're stuck with a non-typesafe Iterator, but you could achieve that with another similar IntegerIterator. Note that this is basically what generics does for you automatically.

    Why are you using such an antiquated JDK?