2010-03-31 5 views
6

Le premier index est défini sur null (vide), mais il n'imprime pas la bonne sortie, pourquoi?Pourquoi list.get (0) .equals (null) ne fonctionne-t-il pas?

//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

Une astuce: 'System.out.println (Arrays.asList (null," High "," High "," High "," High "," High "));' fait ce que vous voulez sans tout cela code supplémentaire. Je dis que c'est le "même" parce que vous ne saviez probablement pas que vous pouviez imprimer des nulls – Pyrolistical

Répondre

6

Je crois que ce que vous voulez faire est de changer,

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

à

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

Merci beaucoup :-). – Jessy

+0

Pas de problème, voir la réponse de Cletus pour une raison plus en profondeur pourquoi cela n'a pas fonctionné comme prévu. –

6

Vous voulez:

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 
    } 
    } 
} 

L'expression choice.get(0).equals(null) devrait jeter un NullPointerException parce que choice.get(0) est null et vous essayez d'appeler une fonction dessus. Pour cette raison anyObject.equals(null) sera toujours retourner false.

+0

merci beaucoup :-) – Jessy

+0

Alors que retourner true pour 'equals (null)' viole le contrat API, il est en fait tout à fait possible. –

Questions connexes