2012-04-04 71 views
1

我已經閱讀了一下,並且我明白,在Java中,您不能更改給定參數的原始值,並期望在方法結束後這些值保持原有值。但我真的很想知道這樣做的好方法。有人能給我一些關於我能做些什麼來使這種方法有效的指針嗎?謝謝。將參數設置爲永久值

/** 
* This will set values in the given array to be "" (or empty strings) if they are null values 
* 
* @param checkNull 
*/ 
public static void setNullValuesBlank(String... checkNull) { 
    for (int i = 0; i < checkNull.length; i++) { 
    String check = checkNull[i]; 
    if (check == null) { 
     check = ""; 
    } 
    } 
} 

編輯

所以我必須將它設置爲數組作爲幾個人提到,如果我建造擺在首位的陣列它的偉大工程,但如果我不這麼做,它不起作用。

這裏的固定方法:

/** 
    * This will set values in the given array to be "" (or empty strings) if they are null values 
    * 
    * @param checkNull 
    */ 
public static void setNullValuesBlank(String... checkNull) { 
    for (int i = 0; i < checkNull.length; i++) { 
    if (checkNull[i] == null) { 
     checkNull[i] = ""; 
    } 
    } 
} 

這裏有一個呼叫它的工作原理:

String s = null; 
String a = null; 
String[] arry = new String[]{s, a}; 
for (int i = 0; i < arry.length; i++) { 
    System.out.println(i + ": " + arry[i]); 
} 
setNullValuesBlank(arry); 
for (int i = 0; i < arry.length; i++) { 
    System.out.println(i + ": " + arry[i]); 
} 

這裏有一個電話在那裏工作,但我希望它:

String q = null; 
String x = null; 
System.out.println("q: " + q); 
System.out.println("x: " + x); 
setNullValuesBlank(q, x); 
System.out.println("q: " + q); 
System.out.println("x: " + x); 

輸出:

q: null 
x: null 
q: null 
x: null 

回答

1

您需要分配給數組:

if (checkNull[i] == null) { 
    checkNull[i] = ""; 
} 

分配到檢查不會改變陣列。

+0

有什麼辦法,我沒有建設擺在首位的陣列? – kentcdodds 2012-04-04 10:23:23

+0

您需要構建它,因爲在常規變量中,您會遇到與原始場景相同的問題,因爲具有參數對象的數組是爲方法調用構造的。 – MByD 2012-04-04 10:26:55

+0

我不完全相信我跟着你,我不明白爲什麼它不會工作,但我認爲你是對的,不幸的是... – kentcdodds 2012-04-04 10:29:26

0
public static void setNullValuesBlank(String... checkNull) 
{ 
    for(int i = 0; i < checkNull.length; i++) if(checkNull[i] == null) checkNull[i] = ""; 
} 
+0

有什麼辦法讓我不必首先構建數組? – kentcdodds 2012-04-04 10:23:54

+0

@kentcdodds是的,將每個字符串作爲參數傳遞,即'setNullValuesBlank(str1,str2,str3);' – 2012-04-04 10:25:26

+0

由於某種原因,這對我不起作用(請參閱我的編輯)。 – kentcdodds 2012-04-04 10:27:32

0

你得值保存到數組:

import java.util.Arrays; 

public class NullCheck { 

    public static void main(final String[] args) { 
     final String[] sa = { null, null }; 
     System.out.println(Arrays.toString(sa)); 
     check(sa); 
     System.out.println(Arrays.toString(sa)); 
    } 

    private static void check(final String... a) { 
     for (int i = 0; i < a.length; i++) { 
      if (a[i] == null) a[i] = ""; 
     } 
    } 

} 
+0

有什麼辦法讓我不必首先構建數組? – kentcdodds 2012-04-04 10:22:30