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