Concept
How can a Java Comparator handle null values?
ComputerScienceOne / Importance of javaequals() and javahashCode() Methods
"Other considerations include null values. How we handle these is a design decision. We could ignore it, in which case such elements would likely result in a NullPointerException and expect the user to prevent or handle such instances. This may be the preferable choice in most instances, in fact. Alternatively, we could handle null objects in the design of our Comparator. Code Sample 36.3 presents a Comparator for our Student class that orders null instances first.\n\n1 Comparator<Student> byNameWithNulls = new Comparator<Student>() {\n\n2 @Override\n\n3 public int compare(Student a, Student b) {\n\n4 if(a == null && b == null) {\n\n5 return 0;\n\n6 } else if(a == null && b != null) {\n\n7 return -1;\n\n8 } else if(a != null && b == null) {\n\n9 return 1;\n\n10 } else {\n\n11 if(a.getLastName().equals(b.getLastName())) {\n\n12 return a.getFirstName().compareTo(b.getFirstName());\n\n13 } else {\n\n14 return a.getLastName().compareTo(b.getLastName());\n\n15 }\n\n16 }\n\n17 }\n\n18 };\n\nCode Sample 36.3.: Handling Null Values in Java Comparators\n\nThis solution only handles null Student values, not null values within the Student object. If the getters used in the Comparator return null values, then we could still have NullPointerExceptions."
Related Ideas
- How should a Comparator order elements in a SortedSet?ComputerScienceOne · Handling javanull values
- What is type juggling in PHP?ComputerScienceOne · Handling Null Values in Java Comparators . . . . . . . . . . . . . . . . .
- How is a Hello World program created in PHP with HTML?ComputerScienceOne · Handling Null Values in Java Comparators . . . . . . . . . . . . . . . . .
- What should you consider when sorting collections or arrays with null values?ComputerScienceOne · Handling javanull values
- How do equals() and hashCode() define object equality in Java?ComputerScienceOne · Common Methods