2012-07-04 54 views
4

我有一個方法如何向Varargs添加新元素?

public boolean findANDsetText (String Description, String ... extra) { 

裏面我想調用另一個方法,並將它傳遞extras但我要添加新的元素(描述),以臨時演員。

 object_for_text = getObject(find_arguments,extra); 

我該如何在java中做到這一點?代碼是什麼樣的?

我厭倦了容納this question的代碼,但無法使其工作。

+1

[如何用額外的a調用可變參數方法來自可變參數法的參數](http://stackoverflow.com/questions/27293989/how-to-call-a-varargs-method-with-an-additional-argument-from-a-varargs-method) – Raedwald

回答

2

extra只是一個String數組。因此:

List<String> extrasList = Arrays.asList(extra); 
extrasList.add(description); 
getObject(find_arguments, extrasList.toArray()); 

您可能需要弄清楚extrasList.toArray()的通用類型。

您可以更快,但更詳細:

String[] extraWithDescription = new String[extra.length + 1]; 
int i = 0; 
for(; i < extra.length; ++i) { 
    extraWithDescription[i] = extra[i]; 
} 
extraWithDescription[i] = description; 
getObject(find_arguments, extraWithDescription); 
+1

我得到'不能在數組類型String []'上調用asList()作爲第一個選項。 – Radek

+0

你的意思是使用'Arrays.asList(extra)'? (見Radek的評論)。 –

+0

現在我得到了'不能在原始類型boolean'上爲'Arrays.asList(extra).add(Description).toArray()'調用toArray()' – Radek

1

你的意思是這樣的?

public boolean findANDsetText(String description, String ... extra) 
{ 
    String[] newArr = new String[extra.length + 1]; 
    int counter = 0; 
    for(String s : extra) newArr[counter++] = s; 
    newArr[counter] = description; 

    // ... 

    Foo object_for_text = getObject(find_arguments, newArr); 

    // ... 
} 
0

它只是這樣......

對待VAR-ARGS如下...

例子:

在你上面的例子中第二個參數是「字符串...額外「

所以你可以這樣用:

extra[0] = "Vivek"; 
extra[1] = "Hello"; 

或者

for (int i=0 ; i<extra.length ; i++) 

    { 

      extra[i] = value; 

    } 
12

爲了擴大在這裏的一些其他的答案,數組複製可以做快一點與

String[] newArr = new String[extra.length + 1]; 
System.arraycopy(extra, 0, newArr, 0, extra.length); 
newArr[extra.length] = Description; 
+0

我得到「方法newArray(String [],int)未定義類型EdumateSuperClass」。我需要做什麼? – Radek

+0

@Radek:與Jonathan的代碼片段無關。 –

+0

好的,那麼我需要做些什麼才能使它工作? – Radek

0

使用Arrays.copyOf(...)

String[] extra2 = Arrays.copyOf(extra, extra.length+1); 
extra2[extra.length] = description; 

object_for_text = getObject(find_arguments,extra2);