【发布时间】:2017-11-09 03:20:31
【问题描述】:
使用 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");
}
}
}
还有我的 main()
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. Student 中的
<T>是什么? 2.你为什么要比较类型S和类型T`? 3.ArrayListnot 扩展Comparable并且最后, 4.BinarySearch接受T的数组作为第一个参数,而不是 arrayList -
1) 那是在尝试随机的东西,看看有什么用。 2)我不是想将 S 类型与 T 类型本身进行比较,但 T[] 由 S 类型组成。
-
searchValue.compareTo(search)当您声明searchValue是S类型并且search是T类型时 -
另外,
Comparable(而不是Comparable<T>)是一个原始类型。 -
1.尝试“随机的事情”不会让你走得太远。做你理解的事,明白你在做什么。 2. “T[] 由类型 S 组成” - 我不确定它是什么意思,但它可能 not 是真的
标签: java generics arraylist icomparable