Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Compare null with integer  RSS feed

 
Dana Ucaed
Ranch Hand
Posts: 350
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers,


I got NPE and it is normal.

How can I compare null with integer?

Thanks in advance!


 
Dana Ucaed
Ranch Hand
Posts: 350
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One solution to avoid NPE is to use Generics.

and other solution?

 
Piet Souris
Rancher
Posts: 1942
66
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use this comparator:

You will still get an error if you put anyting other than an integer, so a generic version is far superiour.
 
Roel De Nijs
Sheriff
Posts: 11333
177
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dana Ucaed wrote:One solution to avoid NPE is to use Generics.

I honestly like to see the code which uses generics to avoid the NPE from being thrown. The root cause of the NPE is the Integer.compareTo() method which is not null-safe. And that's not something which can be fixed using generics.

Dana Ucaed wrote:and other solution?

Either write your own null-safe comparator or (if you are using Java 8) use the nullsFirst (or nullsLast) method from the Comparator interface (as illustrated in Piet's post).
 
Dana Ucaed
Ranch Hand
Posts: 350
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Piet.

Thanks Roel.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!