Reputation: 33
I have a method that will do things to some form of collection. However is it possible to extend the number of types of collections to run the method on? I don't mean a generic collections such as ArrayList but have the method work on ArrayLists, Arrays, Collections, Sets, Hashtables?
Upvotes: 1
Views: 54
Reputation: 10473
While you can't directly extend the method to support the other types you mentioned, you could accomplish this from an API standpoint by overloading methods. For example, if you implement a method to handle all collections:
public <T> void processData(Collection<T> data) { ... }
That will work for all types that implement Collection
. You can overload this method for each type that isn't a Collection
. For example:
public <T> void processData(T[] data) {
processData(Arrays.asList(data));
}
In this example, you are re-using the same method that processes the Collection
structure for arrays too. Each of the types that don't implement Collection
or array will need another specialized overloaded method that either converts it to a Collection
, or more likely, processes that data structure in a way that makes sense for it.
In the end, by overloading the methods, you can call the method by the same name and pass in a variety of types. So from an API standpoint, it always looks like you're calling the same method:
Collection<String> coll = new ArrayList<String>();
int[] arrayOfInts = new int[10];
// You can call processData on both of these types now
processData(coll);
processData(arrayOfInts);
Upvotes: 2