gpt4 book ai didi

java - 实例化Java泛型类对象的问题

转载 作者:行者123 更新时间:2023-12-01 13:06:04 24 4
gpt4 key购买 nike

我一直在兜圈子试图理解 Java 泛型。我在实例化泛型类的对象时遇到问题。对我哪里出错有什么见解吗?

在一个文档中,泛型类:

public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{

public void quickSort(T[] list, int length)
{
recQuickSort(list, 0, length - 1);
}

}

在另一个:

public class TestQuickSort
{

public static void main(String [] args)
{

// define an Integer array of 50000 elements
Integer[] anArray = new Integer[5000];

// load the array with random numbers using
// a for loop and Math.random() method - (int)(Math.random()*50000)
for (int i = 0; i < anArray.length; i++)
{
anArray[i] = (int)(Math.random() * i);
}


// print the first 50 array elemnts with a for loop
// using System.out.print
for (int j = 0; j <= 50; j++) {
System.out.print(anArray[j] + " ");

}
System.out.println();

// define an object of SearchSortAlgorithm with Integer data type
// use this object to call the quickSort method with parameters: your array name and size-5000

SearchSortAlgorithms<Integer> anotherArray = new SearchSortAlgorithms<Integer>(); //This is where I get my error message
anotherArray.quickSort(anArray, 5000);


// print out the first 50 array elements with a for loop
// they have to be sorted now
for (int k = 0; k <= 50; k++) {
System.out.print(anotherArray[k] + " ");
}
}

}

错误消息:

java:39: array required, but SearchSortAlgorithms<java.lang.Integer> found

最佳答案

这个语法

anotherArray[k]
// ^ ^

仅适用于数组类型。 anoterArray 未声明为数组。

您是否想使用anArray

关于java - 实例化Java泛型类对象的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23258885/

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