gpt4 book ai didi

Java : How to return value in generic function

转载 作者:行者123 更新时间:2023-12-03 18:33:03 24 4
gpt4 key购买 nike

我正在用 JAVA 泛型概念测试一些小的实践。

我尝试从一个通用函数返回一个列表,但编译不允许我这样做。

检查下面的代码:

package com.test.generic.method;

import java.util.ArrayList;
import java.util.List;


public class Sample_3<T> {

public <T> List<T> testReturn(T t) {
List<T> list = new ArrayList<T> ();
list.add(t);
return list;
}

public static void main(String a[]) {
String s = "Gunjan";

Sample_3 sample = new Sample_3<String>();
List<String> list =(List<String>) sample.testReturn(sample);


for(String ab : list){
System.out.println(ab);
}

}
}

It gives ClassCastException.

如何从通用函数返回列表?为什么 JAVA 添加了这样的编译时特性?

谢谢,贡詹。

最佳答案

The泛型的目的是允许您自由指定。所以你可以这样做:

public List<T> testReturn(T t){
List<T> list = new ArrayList<T>();
list.add(t);
return list;
}

这将允许您做例如

List<String> a = testReturn("A");
List<Integer> b = testReturn(1);

您的代码的问题在于您的方法的意图并不是真正通用的 - 该方法被编写为返回一个 List <T>在您的代码中实际上不会影响任何东西。

在回答您的进一步问题时 -您已经编写了以下内容:

public class Sample_3 {
public <T> List<T> testReturn(T t) {
List<T> list = new ArrayList<T> ();
list.add(t);
return list;
}

public static void main(String a[]) {
String s = "Gunjan";
// this is wrong - the Sample_3 class is not generic. It does not get a generic type parameter.
Sample_3 sample = new Sample_3<String>();
// this is also wrong. Since the method is generic the "T" you get is the same as the "T" that
// goes into the method. Here your String output type does not match the input type of the method,
// which you've set here as a Sample_3 object
List<String> list =(List<String>) sample.testReturn(sample);

}

您的通用参数 T 设置了可以变化的类型。您可以像上面那样在方法级别执行此操作,也可以在类级别执行此操作:

public class Sample_3<T> {
public List<T> getList(){ ... }
}

例如

 List<Integer> l = new Sample_3<Integer>().getList();
List<String> s = new Sample_3<String>().getList();
List<Calendar> c = new Sample_3<Calendar>().getList();

关于Java : How to return value in generic function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547174/

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