how to implement the method which have parameter same but different signature

ROHIT PATHAK :

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

Marco R. :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115667&siteId=1