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

时间:2017-05-15 03:08:12

标签: 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 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;
}

如果参数来自像这样的数组或地图,我如何调用该方法?这可能吗?

ArrayList arrayList = [299, 296, 301, 297]
crop(arraylist)

3 个答案:

答案 0 :(得分:1)

public ThumborUrlBuilder crop(ArrayList params) {
    if (params.size() != 4 ){
       throw new IllegalArgumentException(...);
    }
    int top = params.get(0);
    int left = params.get(1);
    int bottom = params.get(2);
    int right = params.get(3);
    ...
}

答案 1 :(得分:1)

爪哇:

不,你不能。

你会收到这个错误:

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

Groovy的:

是的,你可以。 检查groovyConsole上的示例代码。

def hello(int a, int b){ 
    println "$a and $b" 
}

hello(1, 2)

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

答案 2 :(得分:0)

这在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));
}