简体   繁体   中英

Java: Passing parameters to a bounded parameter function

In Java, I'm working on a function to return the highest value in an array. I'm writing it such that it does not care about the type of parameter using bounded parameters (I think). I'm getting an error in the main function in detecting the signature of the function.

I followed what I saw in various tutorial pages which don't seem to indicate the call will have any problem.

public static <N extends Number> N getMax (N [] numberArray){
  N value = numberArray [0];
  for (int i = 0; i < numberArray.length; i++){
    if((double) numberArray[i] > (double)  value)
      value = numberArray[i]; 
  }
  return value;
}
public static void main (String [] args ){
  double[] array = {1,2,3,1,-10,2};
  System.out.println(getMax(array));
}

EDIT: A bit of clarification on the issue. I'm doing this as part of an assignment in which I need to write a function that returns the max value of an array. Based upon that, I'm assuming that I cannot expect any particular input and the main function was just demonstrating the issue.

You've specified a primitive array ( double[] ) which cannot be inferred as a Number[] when passing it to getMax . A simple solution would be to use a Double[] instead, as Double extends Number :

public static void main (String[] args) {
    Double[] array = {1D, 2D, 3D, 1D, -10D, 2D};
    System.out.println(getMax(array));
}

Output:

3.0

You can easily convert an array of primitives to an array of containers using methods of the ArrayUtils class, which is in a separate but common library. This will allow you to easily pass arrays of any primitive number types ( int , float , etc.) to your method.

public static void main (String [] args ){
    double[] array = {1,2,3,1,-10,2};
    System.out.println(getMax(ArrayUtils.toObject(array)));
}

While we're at it, Number has a method doubleValue() which hides the cast within its concrete implementations:

if( numberArray[i].doubleValue() > value.doubleValue() )
    value = numberArray[i]; 

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