[英]Is there a way to write a method with generic/dynamic return type?
这只是一个奇怪的问题。
码:
ArrayList<Object> al = new ArrayList<>();
al.add(5);
al.add(5.5);
al.add("abcd");
int a = get(0);
double b = get(1);
String c = get(2);
我知道像0
index这样的数据类型的索引具有int
。
我知道像铸造
int a = (int) list.get(0);
但是,如何编写可以返回任何数据类型并直接分配给变量的get(int index)
方法呢?
谢谢!
您可以做到,但是我不确定这是否是推荐的编程方式:
public static <T> T get (List<?> list, int index) {
return (T) list.get (index);
}
您想要做的是这样的:
//TypelessList is a user-created class with custom casting methods
List typeLess = new TypelessList();
int a = list.getInt(0);
double b = list.getDouble(1);
String c = list.getString(2);
但是,不建议这样做,因为它会破坏您使用的泛型的目的。 投射也是一种缓慢的操作。 您应该做的是制作更具体的列表,例如:
List<Integer> wrappedInts = new ArrayList<Integer>();
wrappedInts.add(Integer.valueOf(5));
int a = wrappedInts.get(0).intValue();
这样,不必要的铸造。
使用Integer类是因为不能在List中使用基本类型。 参考开箱了解更多详细信息。
使用instanceof
确定类。
import java.util.Date;
import java.util.LinkedList;
public class Main
{
static LinkedList list = new LinkedList();
public static void main(String [] args)
{
list.push("String");
list.push(2);
list.push(new Date());
for(Object obj: list)
{
if(obj instanceof String)
System.out.println("String: " + obj);
else if(obj instanceof Integer)
System.out.println("int: " + obj);
else if(obj instanceof Date)
System.out.println("Date: " + obj);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.