Pregunta

Tengo una matriz de objetos parcialmente llena, y cuando los itero, intenté verificar si el objeto seleccionado es null antes de hacer otras cosas con él. Sin embargo, incluso el acto de verificar si es null parece pasar por una NullPointerException . array.length incluirá todos los elementos null también. ¿Cómo se realiza la comprobación de elementos null en una matriz? Por ejemplo, en el siguiente código arrojará un NPE para mí.

Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
    if (someArray[i]!=null) { //do something
    } 
}
¿Fue útil?

Solución

Tienes más cosas de las que dijiste. Ejecuté la siguiente prueba ampliada de su ejemplo:

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");
            }
        }
    }
}

y obtuve el resultado esperado:

$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null

¿Está intentando verificar las longitudes de someArray [index]?

Otros consejos

No lo hace.

Ver abajo. El programa que publicaste se ejecuta como se supone.

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");
  }

Si desea encontrar un elemento nulo particular, debe usar for loop como se dijo anteriormente.

El código dado funciona para mí. Observe que someArray [i] siempre es nulo ya que no ha inicializado la segunda dimensión de la matriz.

Bueno, en primer lugar, ese código no se compila.

Después de eliminar el punto y coma extra después de i ++, se compila y funciona bien para mí.

El código de ejemplo no arroja un NPE. (tampoco debería haber un ';' detrás del i ++)

Luchando si el código se está compilando o no, yo diría que cree una matriz de sixe 5, agregue 2 valores e imprímalos, obtendrá los dos valores y otros serán nulos. La pregunta es si bien el tamaño es 5 pero hay 2 objetos en la matriz. Cómo encontrar cuántos objetos están presentes en la matriz

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;

}

Puede hacerlo en una línea de código (sin declaración de matriz):

object[] someArray = new object[] 
{
    "aaaa",
    3,
    null
};
bool containsSomeNull = someArray.Any(x => x == null);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top