PROJET AUTOBLOG


Shaarli - Les discussions de Shaarli

Archivé

Site original : Shaarli - Les discussions de Shaarli du 23/07/2013

⇐ retour index

java - Comparing Integer objects - Stack Overflow

jeudi 7 mai 2015 à 12:37
GuiGui's Show - Liens 07/05/2015
Petit rappel de prog' Java :
« For reference types, == checks whether the references are equal, i.e. whether they point to the same object.

For primitive types, == checks whether the values are equal.

java.lang.Integer is a reference type. int is a primitive type.

Edit: If one operand is of primitive type, and the other of a reference type that unboxes to a suitable primitive type, == will compare values, not references. »

Comparer deux String : .equals()
Comparer deux Integer ou deux Long : .equals()
Comparer deux int ou deux long : ==
Comparer un Integer ou Long avec un int ou un long : ==

C'est parfois beaucoup plus fourbe que ça :
Map<Long, String> test = new HashMap<Long,String>();
test.put((long) 666, new String("lala"));
System.out.println(test.get(666));
System.out.println(test.get((long) 666));
=> la méthode put() nous impose de caster, mais pas la méthode get() donc le premier sysout affichera null alors que le deuxième retournera le résultat attendu. :P
(Permalink)