0

I am trying to implement Iterator design pattern for generic type. I can not use generic array to store collection, Can someone help me to design Iterator pattern for generic types.

My code here:

public class NamesRepository<T> implements Container<T> {

    public NamesRepository(){
        names = new T[]; // Compilation error
    }
    public T names[];

    @Override
    public Iterator<T> getIterator() {
        return new NameIterator();
    }

    private class NameIterator implements Iterator<T>{
        private int index;

        @Override
        public boolean hasNext() {
            if(index<names.length)
                return true;
            return false;
        }

        @Override
        public T next() {
            if(this.hasNext())
                return names[index++];
            return null;
        }

    }
}
CHowdappaM
  • 1,456
  • 1
  • 11
  • 30

2 Answers2

1

As has been discussed many times before, you can't directly create a generic array using the type parameter. You can follow that question's answers if you must use an array.

However, you can create a List of a type parameter instead. No tricks are necessary, and it's more flexible.

public NamesRepository(){
    names = new ArrayList<T>();  // Easy creation
}
public List<T> names;

Then, your iterator's hasNext() method can compare its index to names.size(), and the next() method can return names.get(index++). You can even implement the other method required for the Iterator interface, remove(), by calling names.remove(index).

Community
  • 1
  • 1
rgettman
  • 167,281
  • 27
  • 248
  • 326
0

You cannot create an array of type parameter. Rather you can store an Object[] array, and type cast the element that you are returning to T:

public NamesRepository(){
    names = new Object[5]; // You forgot size here
}
public Object names[];

And then change the next() method as:

    @Override
    public T next() {
        if(this.hasNext()) {
            @SuppressWarnings("unchecked")
            T value = (T)names[index++];
            return value;
        }
        return null;
    }

And you can really change the hasNext() method to a single line:

    @Override
    public boolean hasNext() {
        return index < names.length;
    }
Community
  • 1
  • 1
Rohit Jain
  • 195,192
  • 43
  • 369
  • 489