Groovy 如何使用ArrayList调用多参数函数?

Groovy 如何使用ArrayList调用多参数函数?,groovy,Groovy,我正在尝试从SDK调用此方法 public ThumborUrlBuilder crop(int top, int left, int bottom, int right) { if (top < 0) { throw new IllegalArgumentException("Top must be greater or equal to zero."); } if (left < 0) { throw new IllegalArgumentException("Left

我正在尝试从SDK调用此方法

public ThumborUrlBuilder crop(int top, int left, int bottom, int right) {
if (top < 0) {
  throw new IllegalArgumentException("Top must be greater or equal to zero.");
}
if (left < 0) {
  throw new IllegalArgumentException("Left must be greater or equal to zero.");
}
if (bottom < 1 || bottom <= top) {
  throw new IllegalArgumentException("Bottom must be greater than zero and top.");
}
if (right < 1 || right <= left) {
  throw new IllegalArgumentException("Right must be greater than zero and left.");
}
hasCrop = true;
cropTop = top;
cropLeft = left;
cropBottom = bottom;
cropRight = right;
return this;
}

这在Java中不可能直接实现,因为函数
crop
需要4个参数

将给定的ArrayList传递到crop函数将导致错误

您可以编写自己的函数来处理
ArrayList
,如下所示:

public ThumboUrlBuilder special_crop(ArrayList arraylist){
    crop(arraylist.get(0),arraylist.get(1),arraylist.get(2),arraylist.get(3));
}

这在Java中不可能直接实现,因为函数
crop
需要4个参数

将给定的ArrayList传递到crop函数将导致错误

您可以编写自己的函数来处理
ArrayList
,如下所示:

public ThumboUrlBuilder special_crop(ArrayList arraylist){
    crop(arraylist.get(0),arraylist.get(1),arraylist.get(2),arraylist.get(3));
}
爪哇: 不,你不能

您将得到以下错误:

Compilation Errors Detected
...
method crop in class Test cannot be applied to given types;
  required: int,int,int,int
  found: java.util.ArrayList<java.lang.Integer>
  reason: actual and formal argument lists differ in length
爪哇: 不,你不能

您将得到以下错误:

Compilation Errors Detected
...
method crop in class Test cannot be applied to given types;
  required: int,int,int,int
  found: java.util.ArrayList<java.lang.Integer>
  reason: actual and formal argument lists differ in length

不可以。您的方法可以接受精确的4个整数值,而不是数组或整数列表。若您愿意,可以在方法中使用可变长度参数并传递一个包含4个值的数组。但那是​ 我认为您不应该这样做,因为它允许调用不带参数或任何数量参数的方法。检查我的答案。不。您的方法可以接受精确的4个整数值,而不是数组或整数列表。若您愿意,可以在方法中使用可变长度参数并传递一个包含4个值的数组。但那是​ 我认为您不应该这样做,因为它允许调用不带参数或任何数量参数的方法。检查我的答案。这是不安全的,因为少于4个元素的列表会引发异常,如果列表中的元素多于4个,则会忽略其他元素。这是不安全的,因为少于4个元素的列表会引发异常,如果列表中的元素多于4个,则会忽略其他元素。无需将该方法命名为其他名称。这是方法重载的一个主要示例,通过为不同类型的参数提供不同的“助手”版本,使方法更易于调用。无需将方法命名为其他名称。这是方法重载的一个主要示例,通过为不同类型的参数提供不同的“助手”版本,使方法更易于调用。
def hello(int a, int b){ 
    println "$a and $b" 
}

hello(1, 2)

def param = [1,2]
hello(param)