0

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 
3
  • Where is aSortedArray declared? What is it declared as? Commented Apr 24, 2014 at 2:47
  • @Sotirios that's a typo--i changed it to anotherArray Commented Apr 24, 2014 at 2:48
  • @tambykojak line 39: System.out.print(anotherArray[k] + " "); Commented Apr 24, 2014 at 2:49

1 Answer 1

1

This syntax

anotherArray[k] // ^ ^ 

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

Did you mean to use anArray?

Sign up to request clarification or add additional context in comments.

4 Comments

that must be my problem. I'm a beginner to java--can you give me a hint as to how I would do so?
Okay, I think I see what you mean. when using the object to call the method on anArray, anArray is sorted directly. I'm not populating the object anotherArray with sorted items from anArray?
I think what he meant was did you mean to write System.out.print(anArray[k] + " "); in the last line
@user25976 You haven't shown all your code, but you seem to be sorting the passed array in place. The important thing to note here is that anotherArray is not an array. The [] don't make sense with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.