Java의 NullPointerException을 피하기 위해 배열 요소인지 확인하는 방법
-
06-07-2019 - |
문제
나는 부분적으로 객체 배열을 가지고 있으며, 그들을 통해 반복 할 때 선택한 객체가 있는지 확인하려고 노력했습니다. null
다른 일을하기 전에. 그러나 그것이 있는지 확인하는 행위조차 null
a NullPointerException
. array.length
모두를 포함합니다 null
요소도. 어떻게 확인 하시겠습니까? null
배열의 요소? 예를 들어 다음 코드에서 NPE를 던질 것입니다.
Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i]!=null) { //do something
}
}
해결책
당신은 당신이 말한 것보다 더 많은 일을하고 있습니다. 예에서 다음과 같은 확장 테스트를 실행했습니다.
public class test {
public static void main(String[] args) {
Object[][] someArray = new Object[5][];
someArray[0] = new Object[10];
someArray[1] = null;
someArray[2] = new Object[1];
someArray[3] = null;
someArray[4] = new Object[5];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i] != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
}
}
}
예상 출력을 얻었습니다.
$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null
somearray [index]의 길이를 확인하려고 할 수 있습니까?
다른 팁
그렇지 않습니다.
아래를 참조하십시오. 게시 한 프로그램은 예상대로 실행됩니다.
C:\oreyes\samples\java\arrays>type ArrayNullTest.java
public class ArrayNullTest {
public static void main( String [] args ) {
Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i]!=null ) {
System.out.println("It wasn't null");
} else {
System.out.printf("Element at %d was null \n", i );
}
}
}
}
C:\oreyes\samples\java\arrays>javac ArrayNullTest.java
C:\oreyes\samples\java\arrays>java ArrayNullTest
Element at 0 was null
Element at 1 was null
Element at 2 was null
Element at 3 was null
Element at 4 was null
C:\oreyes\samples\java\arrays>
String labels[] = { "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.toString(labels).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
------------------------------------------------------------------------------------------
For two Dimensional array
String labels2[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.deepToString(labels2).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
------------------------------------------------------------------------------------------
same for Object Array
String ObjectArray[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };
if(Arrays.deepToString(ObjectArray).indexOf("null") > -1) {
System.out.println("Array Element Must not be null");
(or)
throw new Exception("Array Element Must not be null");
}
특정 NULL 요소를 찾으려면 위의대로 루프에 사용해야합니다.
주어진 코드는 저에게 적합합니다. 배열의 두 번째 차원을 초기화하지 않았기 때문에 Somearray [i]는 항상 무효입니다.
글쎄, 우선 그 코드는 컴파일하지 않습니다.
I ++ 후 추가 세미콜론을 제거한 후에는 컴파일하고 잘 실행됩니다.
예제 코드는 NPE를 던지지 않습니다. (또한 i ++ 뒤에 ';'도있어서는 안됩니다)
코드가 컴파일되는지 여부에 관계없이 Sixe 5의 배열을 생성하고 2 값을 추가하고 인쇄하면 두 값을 얻을 수 있고 다른 값은 null을 얻을 수 있습니다. 문제는 크기가 5이지만 배열에 2 개의 객체가 있습니다. 배열에 얼마나 많은 개체가 있는지 찾는 방법
public static void main(String s[])
{
int firstArray[] = {2, 14, 6, 82, 22};
int secondArray[] = {3, 16, 12, 14, 48, 96};
int number = getCommonMinimumNumber(firstArray, secondArray);
System.out.println("The number is " + number);
}
public static int getCommonMinimumNumber(int firstSeries[], int secondSeries[])
{
Integer result =0;
if ( firstSeries.length !=0 && secondSeries.length !=0 )
{
series(firstSeries);
series(secondSeries);
one : for (int i = 0 ; i < firstSeries.length; i++)
{
for (int j = 0; j < secondSeries.length; j++)
if ( firstSeries[i] ==secondSeries[j])
{
result =firstSeries[i];
break one;
}
else
result = -999;
}
}
else if ( firstSeries == Null || secondSeries == null)
result =-999;
else
result = -999;
return result;
}
public static int[] series(int number[])
{
int temp;
boolean fixed = false;
while(fixed == false)
{
fixed = true;
for ( int i =0 ; i < number.length-1; i++)
{
if ( number[i] > number[i+1])
{
temp = number[i+1];
number[i+1] = number[i];
number[i] = temp;
fixed = false;
}
}
}
/*for ( int i =0 ;i< number.length;i++)
System.out.print(number[i]+",");*/
return number;
}
한 줄의 코드로 수행 할 수 있습니다 (배열 선언없이) :
object[] someArray = new object[]
{
"aaaa",
3,
null
};
bool containsSomeNull = someArray.Any(x => x == null);