Domanda

Ho un array di oggetti parzialmente riempito, e quando eseguo l'iterazione attraverso di essi ho provato a controllare se l'oggetto selezionato è null prima di fare altre cose con esso. Tuttavia, anche l'atto di verificare se è null sembra attraverso un NullPointerException . array.length includerà anche tutti gli elementi null . Come si fa a verificare la presenza di elementi null in un array? Ad esempio, nel codice seguente verrà lanciato un NPE per me.

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

Soluzione

Stai succedendo più cose di quelle che hai detto. Ho eseguito il seguente test ampliato dal tuo esempio:

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

e ha ottenuto l'output previsto:

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

Stai forse cercando di verificare la lunghezza di someArray [indice]?

Altri suggerimenti

Non.

Vedi sotto. Il programma che hai pubblicato funziona come previsto.

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

Se vuoi trovare un particolare elemento null, dovresti usare per loop come detto sopra.

Il codice fornito funziona per me. Si noti che someArray [i] è sempre nullo poiché non è stata inizializzata la seconda dimensione dell'array.

Bene, prima di tutto quel codice non viene compilato.

Dopo aver rimosso il punto e virgola aggiuntivo dopo i ++, viene compilato ed eseguito correttamente per me.

Il codice di esempio non genera un NPE. (non dovrebbe esserci un ';' dietro l'i ++)

Combattendo sul fatto che il codice sia compilato o meno, direi di creare un array di sixe 5, aggiungere 2 valori e stamparli, otterrai i due valori e gli altri sono nulli. La domanda è sebbene la dimensione sia 5 ma ci sono 2 oggetti nell'array. Come trovare quanti oggetti sono presenti nell'array

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;

}

Puoi farlo su una riga di codice (senza dichiarazione dell'array):

object[] someArray = new object[] 
{
    "aaaa",
    3,
    null
};
bool containsSomeNull = someArray.Any(x => x == null);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top