Search code examples
javalistdecoratorfactorytemplate-method-pattern

Add functionalities to List in Java


I need to add the following functionalities over any implementation of List<>: - the resulted object should never show the OutOfBounds Exception for positive indexes - when you call get(x), with x=size, it will automatically increase the list up until size x+1, and will fill the newly created spaces with anything the programmer wishes (except NULL) - remember, the List should be a generic type - otherwise, it should act like a normal List

I know I need to use the Decorator Pattern, at the very least, to add the functionalities, however, I feel should also use some other Design Patterns - maybe Factory or Template, but I'm not exactly sure how.

Can anyone please give at least some hints as to how I can solve the above mentioned task?


Solution

  • class ListImpl<T> extends ArrayList {
    
        private Class<T> tType;
    
        public ListImpl(Class<T> tType) {
            this.tType = tType;
        }
    
        @Override
        public T get(int i) {
            if (i < this.size()) {
                T result = (T) super.get(i);
            } else {
                int resize = 1 + i - this.size();
                // T[] array = (T[]) new Object[resize];
                T[] array
                    = (T[]) java.lang.reflect.Array.newInstance(tType, resize);
                this.addAll(Arrays.asList(array));
            }
            return (T) super.get(i);
        }
    }