2010-03-31 7 views
6

Der erste Index ist auf Null (leer) gesetzt, aber die richtige Ausgabe wird nicht gedruckt, warum?Warum funktioniert list.get (0) .equals (null) nicht?

//set the first index as null and the rest as "High" 
String a []= {null,"High","High","High","High","High"}; 

//add array to arraylist 
ArrayList<Object> choice = new ArrayList<Object>(Arrays.asList(a)); 

for(int i=0; i<choice.size(); i++){ 
    if(i==0){ 
     if(choice.get(0).equals(null)) 
      System.out.println("I am empty"); //it doesn't print this output 
    } 
} 
+1

Ein Trick: 'System.out.println (Arrays.asList (Null," Hoch "," Hoch "," Hoch "," Hoch "," Hoch "));' tut, was Sie wollen, ohne all das zusätzlicher Code Ich sage es ist das "selbe", weil Sie wahrscheinlich nicht wussten, dass Sie Nullen drucken können – Pyrolistical

Antwort

6

Ich glaube, was Sie ändern wollen, ist,

if(choice.get(0).equals(null)) 

zu

if(choice.get(0) == null)) 
+0

Danke :-) sehr viel. – Jessy

+0

Kein Problem, siehe cletus 'Antwort für einen tieferen Grund, warum es nicht wie erwartet funktioniert hat. –

6

Sie wollen:

for (int i=0; i<choice.size(); i++) { 
    if (i==0) { 
    if (choice.get(0) == null) { 
     System.out.println("I am empty"); //it doesn't print this output 
    } 
    } 
} 

Der Ausdruck choice.get(0).equals(null) sollte eine NullPointerException werfen, weil choice.get(0) ist null und Sie versuchen, eine Funktion darauf aufzurufen. Aus diesem Grund anyObject.equals(null) wird immer zurückgeben false.

+0

vielen Dank :-) – Jessy

+0

Die Rückgabe von True für 'equals (null)' verletzt den API-Vertrag, ist aber durchaus möglich. –

Verwandte Themen