由于Java泛型的实现,您不能拥有这样的代码:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
Run Code Online (Sandbox Code Playgroud)
如何在保持类型安全的同时实现这一点?
我在Java论坛上看到了这样的解决方案:
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
Run Code Online (Sandbox Code Playgroud)
但我真的不知道发生了什么.
我怎样才能做到这一点?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试的所有东西总是返回类型Object而不是使用的特定类型.
我正在向我的朋友解释OOP.我无法回答这个问题.(我有多可耻?:()
我只是逃避说,因为OOP描绘了现实世界.在现实世界中,父母可以容纳孩子,但孩子不能容纳父母.OOP也是如此.我知道它很愚蠢.:P
class Parent
{
int prop1;
int prop2;
}
class Child : Parent // class Child extends Parent (in case of Java Lang.)
{
int prop3;
int prop4;
public static void Main()
{
Child aChild = new Child();
Parent aParent = new Parent();
aParent = aChild;// is perfectly valid.
aChild = aParent;// is not valid. Why??
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这个陈述没有效?
aChild = aParent;// is not valid. Why??
Run Code Online (Sandbox Code Playgroud)
因为aChild的成员是aParent成员的超集.那么为什么aChild不能容纳父母.