将多个泛型传递给Java方法

时间:2017-11-09 03:20:31

标签: java generics arraylist icomparable

使用Java。目标是在ArrayList中搜索作为泛型给出的值,也作为通用。

我的学生班(相关部分)

public class Student<T> implements Comparable
{
    private String studName;
    private Integer gradeAverage;

    public Student(String nameIn, int gradeIn)
    {
        studName = nameIn;
        gradeAverage = gradeIn;
    }

    public int compareTo(Object obj)
    {
        Student s1 = (Student)obj;
        return(this.gradeAverage - s1.gradeAverage);
    }
}

我的搜索;认为通用规范可能存在问题

public class SearchMethods<T,S>
{
    public <T extends Comparable, S extends Comparable> void BinarySearch(T[] inputArray, S searchValue)
    {
        boolean found = false;
        for(int i = 0; i < inputArray.length; i++)
        {
            T search = inputArray[i];
            if(searchValue.compareTo(search) == 0)
            {
                System.out.println(searchValue + " is at index " + i);
                found = true;
            }
        }
        if(found == false)
        {
            System.out.println(searchValue + " was not found");
        }
    }    
}

我的主要()

public static void main(String[] args) 
{
    Student studentOne = new Student("James",92);
    Student studentTwo = new Student("Mary",95);
    Student studentThree = new Student("Bobbie",82);
    Student studentFour = new Student("Emily",100);
    Student studentFive = new Student("Joey",88);

    ArrayList<Student> studentList = new ArrayList<Student>();
    studentList.add(studentOne);
    studentList.add(studentTwo);
    studentList.add(studentThree);
    studentList.add(studentFour);
    studentList.add(studentFive);

    SearchMethods<ArrayList, Student> searchMethods = new SearchMethods<ArrayList, Student>();

    searchMethods.BinarySearch(studentList, studentOne);  //Should print that it was found at index 0

给定的编译器错误表明参数不匹配,ArrayList无法转换为T#1 []。但那是仿制药的全部意义,对吧?有趣的是,第二种类型没有给出类似的错误,但是编译器可能还没有提前阅读。

我很确定我的语法在类级别上是正常的,因此错误可能与main()中的调用对象有关。虽然,我可能是错的。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您需要将arraylist转换为数组。检查二进制搜索的参数。

试试这个:

  SearchMethods<ArrayList, Student> searchMethods = new SearchMethods<ArrayList, Student>();

    searchMethods.BinarySearch(studentList.toArray(new Student[studentList.size()]), studentOne);

您还可以更改使用arraylist的BinarySearch。

虽然这不是问题的一部分,但重要的是不要计算compareTo的差异,否则会出现溢出错误。

试试这个:

 class Student<T> implements Comparable
{
private String studName;
private Integer gradeAverage;

public Student(String nameIn, int gradeIn)
{
    studName = nameIn;
    gradeAverage = gradeIn;
}

public int compareTo(Object obj)
{
    Student s1 = (Student)obj;
    if (this.gradeAverage < s1.gradeAverage){
        return -1;
    }
    if(this.gradeAverage == s1.gradeAverage){
        return 0;
    }

    return 1;
}

@Override
public String toString(){
    return "student name="+studName +" grade average= " + gradeAverage;
}
}