java递归方法用泛型
时间: 2023-09-27 14:08:31 浏览: 54
可以使用泛型来编写递归方法,示例代码如下:
```java
public class RecursiveMethod<T> {
public void recursiveMethod(T value) {
if (value instanceof Integer) {
int intValue = (int) value;
if (intValue > 0) {
System.out.println(intValue);
recursiveMethod(intValue - 1);
}
} else if (value instanceof String) {
String strValue = (String) value;
if (strValue.length() > 0) {
System.out.println(strValue.charAt(0));
recursiveMethod(strValue.substring(1));
}
}
}
public static void main(String[] args) {
RecursiveMethod<Integer> integerRecursiveMethod = new RecursiveMethod<>();
integerRecursiveMethod.recursiveMethod(5);
RecursiveMethod<String> stringRecursiveMethod = new RecursiveMethod<>();
stringRecursiveMethod.recursiveMethod("hello");
}
}
```
在上述示例中,我们定义了一个泛型类 `RecursiveMethod<T>`,并在其中定义了一个递归方法 `recursiveMethod(T value)`。该方法接受一个泛型类型的参数 `value`,并根据其类型进行不同的递归操作。在 `main` 方法中,我们分别创建了 `RecursiveMethod<Integer>` 和 `RecursiveMethod<String>` 的实例,分别传入了一个整数和一个字符串进行递归操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)