通过泛型传递数组对象

时间:2015-02-28 03:28:33

标签: java generics

我正在尝试传递一个对象数组,但我一直在犯错误。例如,我正在尝试传递一个Faculty对象数组,但是如何在main上调用它?

//main code

Faculty[] g = new Faculty[2];

g[0]= new Faculty ("Johnson", "Anne", 243, 'F',62,4,27, "FU","Ph.D", "Engineering",3);
g[1]= new Faculty ("Wu", "John", 243, 'F',62,4,27, "FU", "Ph.D", "Engineering", 3);


//I tried the following two lines and it gave me an error

BinarySearch<Object>  eOb =  new BinarySearch<>(g);

BinarySearch<Faculty> eOb =  new BinarySearch<>(g);

这就是我用泛型

声明我的二进制搜索类的方法
public class BinarySearch <T extends Comparable<T>> {

    private T[] array;

    public BinarySearch( T[] a){
        super();
        array = a;
    }

    public int binarySearch(T number){
        // Code

    }
}

这是错误:

  

绑定不匹配:Object类型不是有效替代   有界参数&gt;这种类型   BinarySearch - T无法解析为类型

1 个答案:

答案 0 :(得分:1)

只要Faculty被声明为:

public class Faculty implements Comparable<Faculty> {

}

......第二种形式应该足够了:

BinarySearch<Faculty> eOb =  new BinarySearch<>(g);

Object不是Comparable,所以它不能落在一个范围内。