gpt4 book ai didi

java - 如何使 Java 方法变得通用?

转载 作者:行者123 更新时间:2023-12-01 04:55:36 26 4
gpt4 key购买 nike

我目前正在开发一个项目,我必须使一些方法通用(以使代码更具可读性)。

项目有两个类:BoxMyList 。“Box”的构造函数接受通用参数; 'MyList' 的构造函数只有一个。

public class Box<A, B> {}

这是盒子的类。

public class MyList<T> {}

这就是 MyList 的类。

在“Box”类中,我有一个如下所示的方法:

public static MyList enclose (Box <MyList <Integer, String>> t) {
// Here comes some code that is not important right now.
}

我现在想要的是使这个方法通用,以便它不仅接受像 Box 这样的参数。有人有想法吗?

最佳答案

尚不完全清楚您想要做什么,并且通用参数的数量与您的类不匹配,但也许这可以工作?

public <T> static MyList<T> enclose (Box <MyList <T>, String> t) {
// Here comes some code that is not important right now.
}

或者,如果您想避免谈论 MyList,也许是这样:

public <T> static T enclose (Box <T, String> t) {
// Here comes some code that is not important right now.
}

第二个版本将 Box 对象的第一个泛型参数的类型作为其返回类型...

关于java - 如何使 Java 方法变得通用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14254965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com