0

I want to create a generic method inside a class which takes an array of given type objects and sorts them to return a pair object containing the minimum array item and the maximum array item.

At the moment I get 3 compiler errors:

  • type Object does not take parameters: public <FirstType> Pair sortMinMax(Object<FirstType>[] array)
  • type Object does not take parameters: Object<FirstType> minimum = array[0]
  • type Object does not take parameters: Object<FirstType> maximum = array[0]

Here is my Class:

public class MinMaxArray {

  // takes an array of a given object and returns a pair 
  // of the min and max array elements
  public <FirstType> Pair sortMinMax(Object<FirstType>[] array) {
    Object<FirstType> minimum = array[0];
    Object<FirstType> maximum = array[0];

    // loop through all array items and perform sort
    for (int counter = 1; counter < array.length; counter++) {
      // if this element is less than current min, set as min
      // else if this element is greater than current max, set as max
      if (array[counter].compareTo(minimum) < 0) {
        minimum = array[counter];
      } else if (array[counter].comparTo(maximum) > 0) {
        maximum = array[counter];
      } // end if else new min, max
    } // end for (all array items)

    return new Pair<FirstType, FirstType>(minimum, maximum);
  } // end compare()

} // end MinMaxArray
1
  • 1
    java.lang.Object is not generic Commented Mar 29, 2017 at 10:21

2 Answers 2

3

Firstly, avoid reference arrays. They don't play well with generics. Use List instead.

It's not clear to me if you intend FirstType to be a type or a generic parameter (which would usually be given a single letter name).

If FirstType is a type

public static Pair<FirstType,FirstType> sortMinMax(List<FirstType> things) {

If you mean a generic parameter, look at java.util.Collections.sort.

public static <T extends Comparable<? super T>> void sort(List<T> list) {

So

public static <T extends Comparable<? super T>> Pair<T,T> sortMinMax(List<T> list) {
Sign up to request clarification or add additional context in comments.

Comments

1
type Object does not take parameters

This is what tells you most. Simply, you can write things like Object<T>. The class Object is not parameterized. Lists for example, are.

Also, in order to use the compareTo() method, you need to have something like this:

public <FirstType extends Comparable> Pair sortMinMax(FirstType[] array)

2 Comments

Comparable and Pair are generic so will need arguments. The array is going to make things tricky.
Definitely true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.