2

我已经阅读了一点,我知道在 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
4

3 回答 3

2

您需要分配给数组:

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

分配给检查不会更改数组。

于 2012-04-04T10:08:43.160 回答
0
public static void setNullValuesBlank(String... checkNull)
{
    for(int i = 0; i < checkNull.length; i++) if(checkNull[i] == null) checkNull[i] = "";
}
于 2012-04-04T10:09:06.353 回答
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] = "";
        }
    }

}
于 2012-04-04T10:11:05.277 回答