Note that there are some explanatory texts on larger screens.

plurals
  1. POReturn a generic pair
    text
    copied!<p>I'm trying to create a program which contains a generic method, which contains a type parameter. It should return an instance of the class Pair. I'm not sure how i can return a Pair. The code i have is below:</p> <pre><code>public class MinMaxArray { public static &lt;ArrayType extends Comparable&lt;ArrayType&gt;&gt; ArrayType getMinMax(ArrayType[] anArray) throws IllegalArgumentException { try { ArrayType resultMin = anArray[0]; ArrayType resultMax = anArray[0]; for (int index = 1; index &lt; anArray.length; index++) if (result.compareTo(anArray[index]) &lt; 0) result = anArray[index]; if (result.compareTo(anArray[index]) &gt; 0) result = anArray[index]; return resultMin; return resultMax; }//try catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("Array must be non-empty", e); } catch (NullPointerException e) { throw new IllegalArgumentException("Array must exist", e); } }//getMinMax }//class MinMaxArray </code></pre> <p>Pair class Code:</p> <pre><code>//Two onjects grouped into a pair. public class Pair&lt;FirstType, SecondType&gt; { //The first object. private final FirstType first; //The second object. private final SecondType second; //Constructor is given the two objects. public Pair(FirstType requiredFirst, SecondType requiredSecond) { first = requiredFirst; second = requiredSecond; }//Pair //Return the first object. public FirstType getFirst() { return first; }//GetFirst //Return the second object. public SecondType getSecond() { return second; }//GetSecond }//class Pair </code></pre> <p>I'm not sure how i can get the resultMax and resultMin to return as a Pair. Thanks for the help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload