Here is a code authored by Josh bloch, ( Linkedlist.java)
* #throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
Here I dont see any null ptr check for Collection c.
On contrary effective java very much stresses on parameter validation, emphasizing null pointer check. If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception.
I need to know what I am missing ? In other words why did he not do a null check for addAll function ?
Because Object[] a = c.toArray(); will throw the stated exception anyway, if c is null.
Object[] a = c.toArray(); will obviously throw the NPE. What I would do in this case, would either check at the beginning if the param is null, and then return false (so it doesn't break the runtime flow - Objective-C style), OR assertIsNotNull at the beginning of the method, and specify it in the javadoc (e.g. "the thing must not be null, yo").
But that's just me. That's why APIs must always be well documented.
Related
I have the following Stream:
Stream<T> stream = stream();
T result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst().get();
return result;
However, there is not always a result which gives me the following error:
NoSuchElementException: No value present
So how can I return a null if there is no value present?
You can use Optional.orElse, it's much simpler than checking isPresent:
T result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst().orElse(null);
return result;
Stream#findFirst() returns an Optional which exists specifically so that you don't need to operate on null values.
A container object which may or may not contain a non-null value. If a
value is present, isPresent() will return true and get() will return
the value.
Otherwise, Optional#get() throws a NoSuchElementException.
If a value is present in this Optional, returns the value, otherwise
throws NoSuchElementException.
An Optional will never expose its value if it is null.
If you really have to, just check isPresent() and return null yourself.
Stream<T> stream = stream();
Optional<T> result = stream.filter(t -> {
double x = getX(t);
double y = getY(t);
return (x == tx && y == ty);
}).findFirst();
if (result.isPresent())
return result.get();
return null;
An alternate method for replacing the Optional.get (which more likely than not fails the user's intentions with a NoSuchElementException) is with a more verbose API introduced in JDK10 termed as Optional.orElseThrow(). In author's words -
Optional.get() is an "attractive nuisance" and is too tempting for
programmers, leading to frequent errors. People don't expect a getter
to throw an exception. A replacement API for Optional.get() with
equivalent semantics should be added.
Note :- The underlying implementation of both these APIs is same, yet the latter reads out more clearly that a NoSuchElementException would be thrown by default if the value is not present which inlines to the existing Optional.orElseThrow(Supplier<? extends X> exceptionSupplier) implementation used by consumers as an explicit alternate.
If you wish to continue using the object and not throw any exception, then
Optional.isPresent(object)
is the way to go
This is my implementation of the indexOf method (custom arraylist class)
public int indexOf(String string) {
for(int i = 0; i < size; i++) {
if(strings[i].equalsIgnoreCase(string)){
return i;
}
}
return -1;
}
This is the code that should return null, but which doesn't. I don't understand why
public void indexOf_can_find_null() {
StringArrayList lst = list("1", "2", null, "3", "4", "3", "2", "1");
assertEquals(2, lst.indexOf(null));
}
This will never work. You cannot use the equalsIgnoreCase() to test for null.
The equalsIgnoreCase() method does a comparison on the the VALUES of the strings. A null string has no value. When you use null you are saying that this String object does not reference anything, hence it has no value, therefore nothing with a value can ever be equal to it. If you had a null object BEFORE calling equalsIgnoreCase(), then a NullReferenceException would be thrown, so it doesn't work in either direction.
If you used the == operator it would allow you to test the reference of the string, which null would work out, however this cannot be used for string comparison. If you really wanted this to work you'd need to combine the methods:
if(strings[i] != null && strings[i].equalsIgnoreCase(string))
return i;
else if(strings[i] == null && string == null)
return i;
Because of NullPointerException. When i=2, strings[i] is null, then strings[i].equalsIgnoreCase(string) will throw a NullPointerException.
PS: without the code of list(), this is just a wild guess
In your case, when i = 2, you'll have:
string[2].equalsIgnoreCase(string) evaluates to null.equalsIgnoreCase(string)
This will throw a null pointer exception as a null reference is used.
I've got stuck here in a simply method because I can't get it compiling.
I'm doing for each loop of objList which is an ArrayList<anObject>. I know the compiler can't get it compiled because there is no "Top-Level Return".
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node;
}
}
}
Also I don't know what to return when the conditions doesn't met. I can't return a anObject because there isn't.
Hope you can help me to provide solutions.
There are several things you can do:
Return null
Not the best practice, though, because the method's client will be forced to handle the possibly returned null (and if he doesn't, a NullPointerException can be thrown).
Your method would look like:
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return obj;
}
}
return null;
}
In this case, the client will have to deal with the case of null results:
anObject result = getObjByID(someId);
if (result != null) {
//proceed
}
Throw IllegalArgumentException (or some other Exception)
You can throw IllegalArgumentException to denote there's no corresponding Node for the provided id. The client will be forced to handle the exception.
Your method would look like:
anObject getObjByID(int id) throws IllegalArgumentException {
for(anObject obj : objList ){
if (obj.getID() == id){
return obj;
}
}
throw new IllegalArgumentException("Invalid index");
}
and the client will be have to handle the exception:
try {
anObject result = getObjByID(someId);
//proceed
} catch (IllegalArgumentException e) {
//handle the exception
}
Use Java8's Optional<T> type
Java8 introduces the Optonal<T> class, which is something like an alien - it may or it may not exist. Specifying the return type of a method to be Optional<T> helps the client have the awareness that a return value may exist, or may not.
Your method would look like:
Optional<anObject> getObjByID(int id){
Optional<anObject> result = Optional.empty();
for(anObject obj : objList ){
if (obj.getID() == id){
result = Optional.of(obj);
}
}
return result;
}
The client will use this method like this:
Optional<anObject> result = getObjByID(someId);
if (result.isPresent()) {
anObject realResultObject = result.get();
}
You have to return some default value if your searching object not found. you can return null here.
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node; // will return when searching matched
}
}
return null; // will return matching not found.
}
Throwing an exception is another option you can use.
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node;
}
}
throw new MyException("Element Not Found");
}
You need to return a value in every case. Null seems good here.
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node;
}
}
return null;
}
You always need to consider that you can call this method and the if statement doesnt equal to true. Therefore what should your method return? It needs either an object of type anObject or you return null. Sometimes it makes sense to throw an exception if this case should never happen.
Also I don't know what to return when the conditions doesn't met.
That really depends on your logic. If you want to allow null, you shouldn't return it if no object is found, you can create your own object that indicates that the object was not found or throw an exception that will be caught later.
If your object cannot be null, you can assume that null is returned when the object is not found.
If you're using Java 8, you have much more better alternatives, see Optional.
Please follow Java naming conventions
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node;
}
}
return null;
}
You could simply throw an exception with an specific message, which is a good solution in my opinion. But this will intrerrupt the flow on the program if not catched.
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node;
}
}
thronw new UserDefinedException("Item not found in list");
}
From ls-8.4.7
If a method is declared to have a return type, then a compile-time error occurs if the body of the method can complete normally (§14.1).
Mean return your expected object to complete method or return null.
And From jls-8.4.5
Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:
If R1 is void then R2 is void.
If R1 is a primitive type, then R2 is identical to R1.
If R1 is a reference type then:
R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or
R1 = |R2|
Means if you are using java 7 then return Type should be as above condition.
If you are using java 8 check JLS 8.4.5. Method Result
There are basically two different options:
Not finding an object is a valid scenario; then you might return null. Or maybe some special Singleton object that represents an empty search result - as many people argue that using null in such a context is a bad idea (it forces the caller of your method to check for null; or you risk a NullPointerExceptions)
Not finding an object is an error that should not occur: then you can simply throw an exception after the loop.
If I have a method like this:
public Object getObject(int i) {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
} else {
return
}
}
Is this the best way to deal with array index out of bounds errors, and what should I return in the else statement, null?
There is no absolute answer for this question, it depends on many things. However, if null is not a legal value, I would return null, if it's legal value I would throw an exception.
/**
* ...
* #return The element at index i, null if out of bounds.
*/
public Object getObject(int i) {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
}
return null;
}
Or if null is a legal value:
public Object getObject(int i) throw IndexOutOfBoundsException {
if (i >= 0 && i < objectList.size()) {
return objectList.get(i);
}
throw new IndexOutOfBoundsException();
}
There is no such thing as "the best way", everything depends on your particular application. If "null" is somewhat recognizable (there are no nulls in your container) it can be an option. In some cases returning 0 may be the good option (when dealing with strictly positive number containers) and in others you could return element at i % size (so your container is cyclic). In general - it is always risky to return anything when asked for non existing element.
The most "frequent" approach is to raise an exception instead of returning anything.
You could implement the Null Object pattern.
Or you could implement a clamp, i.e. if the index is negative then return element at index 0 or if it is greater than or equal to size then return element at index size-1
But in your particular case the best thing to do is to raise an exception. This is what List#get does per default, so just leave it like that.
The reason is that you are explicitly asking for the value of an element at a certain index, i.e you expect that it is available. If not then there must be something wrong with the logic you use to determine that index.
I would throw an exception when the method is called with an illegal index. It does not make much sense to return anything for illegal calls.
Code would look like this:
public Object getObject(int i) {
return objectList.get(i);
}
Furthermore returning null pollutes other code with boilerplate null-checks.
Finally you're in good neighborhood with Java's List specification of List.get(int) when raising IndexOutOfBoundsException in such cases.
Its true there is no such thing like "best way" but you can handle exceptions by thinking what can cause them not to go to that point atleast.
public Object getObject(int i)
{
if(objectList == null || ojbectList.size()<=i)
return null;
if (i >= 0 && i < objectList.size())
{
return objectList.get(i);
}
}
Approach one.
if (graphType.equals("All") || graphType.equals("ALL"))
Aprroach two.
if ("All".equals(graphType) || "ALL".equals(graphType))
What is the difference between these two approaches?
Why the below one is better?
The second one is better, as if graphType is null, the first code snippet will throw a NullPointerException.
Note that you can simplify your code using "ALL".equalsIgnoreCase(graphType) (if you accept values such as AlL or aLL...)
Edit regarding your comment:
If graphType is null, in the first case, you will get a NullPointerException. In the second case, the evaluation of the equals method will be false, as "someString".equals(null); always returns false:
Here is the code of the String.equals(String) method:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
(source)
The interesting line is if (anObject instanceof String) {. When you call the instanceof statement on a null object, this test always returns false. That's why "anyString".equals(null); will return false.
I feel the need to present a contrarian viewpoint to the accepted answer:
The first one is better, precisely because it will throw a NullPointerException in the case where graphType is null.
Generally, if an unexpected condition is found, you want to halt and throw an Exception as early as possible, otherwise you may continue to execute the program in an invalid state and the bug may become fiendishly difficult to track down.
This is sometimes referred to as the "fail-fast" principle.
romaintaz answer is absolutely correct. However, if you're like me, you might prefer to use the first approach to make your code easier to read. This is where assertions come into play:
assert graphType != null : "graphType is null";
if (graphType.equals("All") || graphType.equals("ALL"))
The question is whether your users will find a creative way to make graphType = null once you've finished testing.
The other thing I don't like about the second approach is that it fails silently in the case that graphType is unexpectedly null -- It prevents a runtime error, but may present a bug that's difficult to track down.