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

时间:2014-04-24 02:45:58

标签: java generics

我一直在试图理解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

1 个答案:

答案 0 :(得分:1)

此语法

anotherArray[k]
         // ^ ^

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

您的意思是使用anArray吗?