java泛型:定义对象

时间:2014-04-23 05:04:41

标签: java generics

我正在尝试学习Java并且无法理解泛型。我正在尝试定义Integer数据类型的对象,然后使用该对象来调用泛型方法。

在API和一些网络资源的指导下,我一直在尝试各种各样的事情,但我不知道我是否在简单定义对象方面走在正确的轨道上。

SearchSortAlgorithms.java:

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

TestQuickSort.java

public class TestQuickSort
{  
    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);
    }


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

    Integer aSortedArray = new Integer(5000);
    public void quickSort(anArray, 5000) {
    TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
    return aSortedArray.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(aSortedArray[k] + " ");
    }

  }

}

这些行的错误:

    public int TestQuickSort () {
        TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
        aSortedArray = quickSort(anArray, 5000);
    }

-Illegal表达式:我想知道我创建构造函数的尝试是否正确 - ;预期

1 个答案:

答案 0 :(得分:1)

忽略代码中的任何其他潜在错误(或由于此处向我们展示),您试图在main中声明另一种方法。

public int SearchSortAlgorithm () {
    TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
    aSortedArray = quickSort(anArray, 5000);
}

需要移出main。并且还固定为实际返回intmain的签名应为public static void main(String[] args)

虽然,它确实应该返回int[]而不是......

public static int[] searchSortAlgorithm (final int[] anArray) {
    TestQuickSort<Integer> aSortedArray = new TestQuickSort<Integer>();
    return quickSort(anArray, 5000);
}

...并在你的main方法中调用......

int[] aSortedArray = searchSortAlgorithm(anArray);
for (int k = 0; k <= 50; k++) { // would be better to use aSortedArray.length
  System.out.print(aSortedArray[k] + " ");
}