[英]Java varargs with 2-dimensional arrays
問題留在這里,因為人們回答了它,我的問題是我使用的API的版本與我的文檔不同步....你實際上可以做到這一點。
有沒有辦法在Java中使用二維數組作為參數的參數,該參數需要一個數組變量?
我試圖打電話的功能是
public Long sadd(final byte[] key, final byte[]... members) {
我有一個2-d字節數組(byte [] [] data = blah)
但是,如果我試着打電話
sadd(key,data);
我得到以下編譯器錯誤:
(實際參數byte [] []不能通過方法調用轉換轉換為byte []
有沒有辦法使用二維數組作為數組類型的變量?
以下適用於我。 也許你沒有做你認為你在做的事情?
@Test
public void test_varargs() {
byte[] x = new byte[] { 1, 2, 3};
byte[] y = new byte[] { 0, 1, 2};
assertEquals(9L, sum(x,y));
byte[][] z = new byte[][] { x,y };
assertEquals(9L, sum(z));
}
public long sum(final byte[]... members) {
long sum = 0;
for (byte[] member : members) {
for (byte x : member) {
sum += x;
}
}
return sum;
}
你可以提供更多的代碼,因為這可以為我編譯。
byte[][] data = new byte[1][];
byte[] key = new byte[1];
long sadd = sadd(key, data);
class A {
void show(int[] ax,int[]...arr) {
for (int is : ax) {
System.out.println(is);
}
for (int[] a : arr) {
for (int i : a) {
System.out.println(i);
}
}
}
}
public class abc{
public static void main(String[] args) {
A a = new A();
int[] arr1= new int[]{10,20};
int[][] arr2 = new int[][] { { 10, 20 }, { 20, 20 }, { 30, 20 } };
a.show(arr1,arr2);
}
}
這里我使用2-d數組作為var args參數,使用1-d數組作為固定參數。 如果這可以幫助您,請參考此代碼! :)
這是不可能的,因為編譯器無法推斷出這兩個維度。 使用一維數組時,您可以將數組的長度確定為輔助參數的數量(非必需參數)。
例如:假設你的方法定義包括n
強制性參數,並在運行時,需要提供m
更多的參數。 那些m
參數將構成輔助參數的數組。 長度是m
。 在二維數組的情況下,編譯器必須為數組提出兩個維度: dimension1 * dimension2 = m
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.