构造函数参数中的泛型

时间:2014-01-31 16:03:49

标签: java generics

我知道这是一个非常愚蠢的问题,因为我曾经知道过这样的事情。但是我现在很难完成这项工作。 我有一个类的构造函数,它应该得到一个ArrayList,它充满了实现我的接口名为CollisionObserver的Objects。这是我的构造函数头:

public Cursor(GL gl, LibraryFinger finger, Vector direction, float radius, 
       int index, ArrayList<T extends CollisionObserver> observerList)

有谁可以告诉我哪里犯了大错? 我也尝试了ArrayList<CollisionObserver>,但是这也行不通,因为当我使用实现CollisionObserver的Objects调用构造函数时,错误消息表明构造函数是unifined。

好的,这是完整的Cursor类:

public class Cursor implements CollisionSubject{

private Vector direction;
private GL gl;
private float radius;
private LibraryFinger finger;
private GLUT glut;
protected static float[] sphere_center = new float[3];
private ArrayList<CollisionObserver> observer = new ArrayList<CollisionObserver>();

public Cursor(GL gl, LibraryFinger finger, Vector direction, float radius, int index, ArrayList<T extends CollisionObserver> observerList){
    this.gl = gl;
    this.finger = finger;
    this.direction = direction;
    this.radius = radius;
    glut = new GLUT();

//Finetuning for fingermovements! The vector delivered by the LeapListener is to be considered as
//raw-data. It has to be adjusted to the environment in which the fingertracking is used.
    sphere_center[0] = (float) (finger.getX()/15);
    sphere_center[1] = (float) ((finger.getY()/20)*-1);
    sphere_center[2] = (float) (finger.getZ()/5);

    gl.glTranslatef(sphere_center[0], sphere_center[1], sphere_center[2]);
    gl.glEnable(GL.GL_CULL_FACE);
    gl.glCullFace(GL.GL_BACK);
    gl.glColor3f(0.757f, 0.804f, 0.804f);

    glut.glutSolidSphere(radius, 16, 16);
    for (int i = 0; i < index; i++){
        registerCollisionObserver(observerList.get(i));
    }
    myPosition();
}

@Override
public void registerCollisionObserver(CollisionObserver o) {
    observer.add(o);        
}

@Override
public void removeCollisionObserver(CollisionObserver o) {
    if (!observer.isEmpty()) {
        int i = observer.indexOf(o);
        if (i >= 0)
            observer.remove(i);
    }
}


@Override
public void myPosition() {
    for (int i = 0; i < observer.size(); i++) {
        CollisionObserver o = observer.get(i);
        o.collision(finger, direction, radius);
    }
}

以下是我如何调用构造函数。我在两个不同的课程中这样做。头等舱:

private ArrayList<Picture> picList = new ArrayList<Picture>();

“Picture”类型实现了CollisionObserver接口

 Cursor finger = new Cursor(gl, lfl[i], listener.getFl().get(i).direction(), 0.5f, picList.size(), picList);

与第二类相同。 Type Shelf实现了CollisionObserver接口:

    private ArrayList<Shelf> shelfList = new ArrayList<Shelf>();
    Cursor finger = new Cursor(gl, lfl[i], listener.getFl().get(i).direction(), 0.5f, shelfList.size(), shelfList);

2 个答案:

答案 0 :(得分:2)

在你的一个构造函数参数中,你声明了这个:

ArrayList<T extends CollisionObserver>

T来自哪里?如果您希望此ArrayList包含与此类类型绑定的元素,则此处使用T将是合适的。

从它看起来,你想要一个只实现CollisionObserver的对象列表,所以这就是你想要的声明:

ArrayList<? extends CollisionObserver>

答案 1 :(得分:1)

您需要声明您的类使用泛型类型T

示例

public class MyClass<T>