Using Java generics in interfaces that return collections. Best practice Traps?

Today I came across some code that turned out to be dubious. Here's a simplified example (not realistic).

public interface IListable {
    //returns first n items from list
    public ArrayList getFirstNThings(int n);

    //returns last n items from list
    public ArrayList getLastNThings(int n);
}

Then there is such a constructor:

public GroceryList implements IListable {
    private ArrayList<GroceryItem> groceries;

    public GroceryList() {
        this.groceries = new ArrayList<GroceryItem>();
    }

    public ArrayList<GroceryItem> getFirstNThings(int n) {
        ArrayList<GroceryItem> firstNThings = new ArrayList<GroceryItem>();
        for (int i=0; i < n; i++) {
            firstNThings.add(this.groceries.get(i));
        }
        return firstNThings
     }

     public ArrayList<GroceryItem> getLastNThings(int n) {
         ArrayList<GroceryItem> lastNThings = new ArrayList<GroceryItem>();
         for (int i=this.groceries.size(); i < this.groceries.size()-n; i--) {
           lastNThings.add(this.groceries.get(i-1);
         }
         return lastNThings;
      }
}

Ignore any implementation problems you may find in this (I also found some). What I get is that the interface does not use any general parameter type for ArrayList (e.g. ArrayList <?>), But the developer of the interface method does (i.e. ArrayList <GroceryList>). Other developers can return ArrayLists with any other type parameters, no?

, : ? -? ? ? , , , , ?

+5
2

IListable , :

public interface IListable<T> {
  //returns first n items from list
  public ArrayList<T> getFirstNThings(int n);

  //returns last n items from list
  public ArrayList<T> getLastNThings(int n);
}

, ? . , .

public interface IListable {
  //returns first n items from list
  public ArrayList<?> getFirstNThings(int n);

  //returns last n items from list
  public ArrayList<?> getLastNThings(int n);
}

, , . IListable, . GroceryList, GroceryItems. , . , List<Foo> get(), ArrayList<Foo> get().

+5

List<?> , null.

Java . , .

, List<? extends User> List<? super User>

, , , PECS . , .

0

All Articles