简体   繁体   中英

issue instantiating object of Java generic class

I've been going around in circles trying to understand Java generics. I'm having trouble instantiating an object of a generic class. Any insight to where I'm going wrong?

In one document, the generic class:

public class SearchSortAlgorithms<T> implements SearchSortADT<T>
{
  …
    public void quickSort(T[] list, int length)
    {
        recQuickSort(list, 0, length - 1);
    }
  …
}

In another:

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] + " ");
        } 
   }

}

Error message:

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

This syntax

anotherArray[k]
         // ^ ^

only works with array types. anoterArray is not declared as an array.

Did you mean to use anArray ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM