gpt4 book ai didi

java - 将多个泛型传递给 Java 方法

转载 作者:行者123 更新时间:2023-11-30 06:26:01 24 4
gpt4 key购买 nike

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

我的学生类(class)(相关部分)

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() 中的调用对象有关。不过,我可能是错的。

提前致谢!

最佳答案

您需要将 arraylist 转换为数组。检查二分查找的参数。

试试这个:

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

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

您还可以更改使用数组列表的 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;
}
}

关于java - 将多个泛型传递给 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47193346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com