简体   繁体   English

Java:将参数传递给有界参数函数

[英]Java: Passing parameters to a bounded parameter function

In Java, I'm working on a function to return the highest value in an array. 在Java中,我正在研究一个函数以返回数组中的最大值。 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 . 您已指定一个原始数组( double[] ),将其传递给getMax时不能将其推断为Number[] A simple solution would be to use a Double[] instead, as Double extends Number : 一个简单的解决方案是改用Double[] ,因为Double扩展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. 您可以使用ArrayUtils类的方法轻松地ArrayUtils 语数组转换为容器数组,该类位于单独但通用的库中。 This will allow you to easily pass arrays of any primitive number types ( int , float , etc.) to your method. 这将使您可以轻松地将任何原始数字类型( intfloat等)的数组传递给您的方法。

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: 当我们使用它时, Number具有一个doubleValue()方法,该方法将doubleValue()隐藏在其具体实现中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM