如何实现参数相同但签名不同的方法

我必须实现具有相同功能但返回类型不同且函数参数也相同的函数。


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;

}  

这里Base和Subclass是已经定义的类。


应该只命名一个方法,remove因为功能相同,所以如果我仅仅因为不同的数据类型而两次实现相同的方法,就会出现冗余


炎炎设计
浏览 141回答 3
3回答

忽然笑

如果您的方法具有相同的逻辑但参数类型不同,则可以创建此类方法的通用版本。在您的情况下,这种方法如下所示:&nbsp; &nbsp; public static <T> List<T> remove(List<T> arrange) {&nbsp; &nbsp; &nbsp; &nbsp; List<T> update = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; for (T arranging : arrange) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //For-loop body here&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return update;&nbsp; &nbsp; }然后您可以将此方法与任何T(Base或Subclass) 一起使用,该方法将处理列表中的元素作为参数传递并返回适当的类型:&nbsp; &nbsp; &nbsp; &nbsp; List<Subclass> one = ...;&nbsp; &nbsp; &nbsp; &nbsp; one = remove(one);&nbsp; &nbsp; &nbsp; &nbsp; List<Base> two = ...;&nbsp; &nbsp; &nbsp; &nbsp; two = remove(two);希望这可以帮助。

红颜莎娜

您在这里需要的是泛型方法。可以使用不同类型的参数调用的单个泛型方法声明。您需要的通用函数如下所示:public&nbsp;static&nbsp;<&nbsp;E&nbsp;>&nbsp;List<E>&nbsp;remove(&nbsp;List<E>&nbsp;arrange&nbsp;)&nbsp;{...}如果有多个泛型类型并且一个是另一个的子类(例如 BaseClass 和 SubClass),声明将如下所示public&nbsp;static&nbsp;<&nbsp;E,&nbsp;F&nbsp;>&nbsp;List<E>&nbsp;remove(&nbsp;List<F&nbsp;extends&nbsp;E>&nbsp;arrange&nbsp;)&nbsp;{...}更多信息,您可以参考https://www.tutorialspoint.com/java/java_generics.htm

智慧大石

我看到您所处的情况是,两种方法几乎可以做同样的事情,但向调用者呈现的结果却不同。如果返回类型的域较大,则使用泛型。&nbsp;public static E remove(List<E> arrange)如果返回类型有限,您可能会在 Base 和 SubClass 之间建立关系。并使用协方差来处理多种返回类型。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java