Reputation: 3
I have to implement the function which have the same functionality but different return type and the parameter of the function is also same.
public static List<Base> remove(List<Subclass> arrange ) {
List<Base>update = new ArrayList<>();
for(Subclass arranging : arrange){
//For-loop body here
}
return update;
}
public static List<Subclass> remove(List<Subclass> arrange ) {
List<Subclass>update = new ArrayList<>();
for(Subclass arranging : arrange){
//For-loop body here
}
return update;
}
Here Base
and Subclass
are the classes already defined.
Only one method should be there named remove
because the functionality is same so redundancy will occur if I implement the same method twice just because of different datatype
Upvotes: 0
Views: 732
Reputation: 2720
If you have a method which has the same logic with different parameter types you can create a generic version of such method. In your case such a method would look like:
public static <T> List<T> remove(List<T> arrange) {
List<T> update = new ArrayList<>();
for (T arranging : arrange) {
//For-loop body here
}
return update;
}
Then you can use this method with any T
(Base
or Subclass
) and the method will work with the elements of the list pass as argument and return the appropriate type as well:
List<Subclass> one = ...;
one = remove(one);
List<Base> two = ...;
two = remove(two);
Hope this helps.
Upvotes: 1
Reputation: 51
I see you are in a situation where two methods does almost the same thing but present the result differently to the caller. Use generics if the domain of return type is larger.
public static E remove(List<E> arrange)
If the return types are limited you might develop a relationship between Base and SubClass. And use co-variances to deal with multiple return types.
Upvotes: 0
Reputation: 1040
What you need here is called generic method.
A single generic method declaration that can be called with arguments of different types. The generic function you need will look like this:
public static < E > List<E> remove( List<E> arrange ) {...}
In the case that there are more than one generic type and one is the subclass of the other (e.g. BaseClass and SubClass), the declaration will look like
public static < E, F > List<E> remove( List<F extends E> arrange ) {...}
For more information, you can refer to https://www.tutorialspoint.com/java/java_generics.htm
Upvotes: 0