Javadoc of ArrayUtils.isNotEmpty is faulty? - java

The javadoc of ArrayUtils.isNotEmpty() in Apache Commons Lang seems to be wrong. Or, at least, misleading. It says
Returns:
true if the array is not empty or not null
In my understanding, an empty array is not null. So, according to the above definition, isNotEmpty() should return true for an empty array, which is counterintuitive.
Wouldn't
Returns:
true if the array is not null and not empty
be more correct?

Wouldn't
Returns: true if the array is not null and not empty
be more correct?
Yes you are right. The doc is a bit misleading. In fact, if you see the source code, it does exactly that:
public static boolean isNotEmpty(Object[] array) {
return (array != null && array.length != 0);
}

In my understanding, an empty array is not null.
Not correct. Counterexample:
int a[];
a is an empty array (as it doesn't contain anything), and it's also null since it wasn't initialized.
In this case, isNotEmpty will return false, since it is empty.

Related

Java printing empty array error

This is my very simple code, with data being an empty double array
private void findLast(){
double empty[] = new double[0];
if(data == empty){
throw new ArrayIndexOutOfBoundsException(" Array is empty");
}else{
System.out.println(data[data.length-1]);
}
}
When I run the code I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
My question is, shouldn't the "throw" and "if" stop the "else" from running? And how do I fix the code so it runs properly?
== tests for reference equality for reference types such as arrays.
empty == empty is true
empty == new double[0] is false.
If you need to find if an array is empty, use:
if (data.length == 0) {
In java, the == operator checks if the two variables reference the same object, not if the two objects that the variables reference have equivalent values. So, even if both empty and data are double arrays of size 0, data == empty will never be true because they don't reference the same object.
As a side note, I'm not really sure there's any good reason for you to be doing this and an array of size 0 doesn't have an element at length - 1. If empty has zero elements, what is the point of creating it? if it doesn't have zero elements and you want to know if there is nothing stored into it, then you should know that arrays always have something stored in them after being initialized.
if(data.length==empty.length)
{
throw new ArrayIndexOutOfBoundsException(" Array is empty");
}else{
System.out.println(data[data.length-1]);
}

System.out.println() of Stream#reduce() unexpectedly prints "Optional[]" around result

I started to learn Lambda expressions of Java 8, and wrote below program to get sum of all numbers in the list:
import java.util.Arrays;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
List<Integer> number = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(number.stream().reduce((c,e) -> {
return c + e;
}));
}
}
I was expecting the output to be:
15
but I got:
Optional[15]
Java version: 1.8.0_45
Please explain what does Optional[] means in the output?
Does it has any significance in Java 8?
From the Java Docs for Stream#reduce(), we see that the reduce operation returns an Optional<T>. An Optional simply wraps a value if there is a value present, otherwise is "empty".
Important operations on Optional include Optional#isPresent, which lets you know if there is something in the Optional or not, Optional#get, which returns the T wrapped in the Optional and throws an exception if called on Empty, and Optional#orElse which returns the T wrapped in the Optional if present, or the returns the default value provided if called on Empty.
For your case, the rationale behind reduce() returning an Optional<Integer> is that the list you're trying to reduce may be empty. In that case, the Integer that should be returned is not well defined. For your specific intention 0 would be acceptable (As the sum of the elements in an empty list is 0), thus you can get the sum as follows:
int sum = number.stream().reduce((c,e) -> c + e).orElse(0);
That way, even if the list is empty, you will still get a result that defines the sum of the list.
reduce(BinaryOperator<T> accumulator):
Returns an Optional describing the result of the reduction
Optional:
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.
The reason reduce() returns an Optional, is because the stream might be empty, in which case there would be nothing to reduce, aka no value, and an Optional.empty() would be returned.
In order to avoid Optional in the return you can call to this other method https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce-T-java.util.function.BinaryOperator- Just add the identity: "0" before adding the lambda expression. Note that now there is only a 0 as a fist parameter to the reduce call.
System.out.println(number.stream().reduce(0,(c,e) -> {
return c + e;
}));
returns just
15
Got it, thanks #Mshnik and #TimoSta. According to source code of Optional<> which overrides toString method
#Override
public String toString() {
return value != null
? String.format("Optional[%s]", value)
: "Optional.empty";
}
Above code adds that Optional[] in my output stream.
From java.lang.Object.Optional:
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.
Optional offers two different primary methods for retrieving its value.
public T get() simply returns the value enclosed in the Optional, but throws a NoSuchElementException if the Optional does not wrap a value.
orElse(T other) returns the value enclosed in the Optional or other if the Optional does not enclose a value.
EDIT (thanks #Brian Goetz):
Generally, orElse() is a better choice since get() returns a NoSuchElementException if the Optional contains a null value. True, in this case you will always recieve a value in Optional but it's still good practice to primarily use orElse().
So, in your case, you would change
System.out.println(number.stream().reduce((c,e) -> {
return c + e;
}));
to:
System.out.println(number.stream().reduce((c,e) -> {
return c + e;
}).orElse(0));
which will return the desired value of 15.
And as #Brian Goetz said in the comments, if you really wanted to make it succinct you could use Integer::sum and a method reference:
System.out.println(number.stream.reduce(Integer::sum).orElse(0))
which is equivalent to using the longer lambda.

What is the cleanest way to compare an int with a potentially null Integer in Java?

Map<String,Integer> m;
m = new TreeMap<String,Integer>();
Is it good practice to add the following cast just to avoid the null pointer exception when m.get() is null.
System.out.println( ((Integer) 8).equals( m.get("null") ) ); // returns false
Alternatively with a prior null check it starts to look a bit ugly.
System.out.println( m.contains("null") != null && m.get("null").equals( 8 ) );
Is there a better way to write this? Thanks.
The == operator doesn't compare values, but references.
You should use the .equals() method, instead, applied to the Integer variable (for which you are sure that is not null and NPE won't be thrown):
Integer eight = 8; //autoboxed
System.out.println(eight.equals(m.get("null")));
This will print false even the m.get("null") returns null.
No, because it will not work. You can't compare two Integer with ==, as that compares references and not the integer values. See more info in this question
You'll need a helper method, such as:
boolean safeIntegerCompare(Integer a, int b)
{
if (a != null)
return a.intValue() == b;
return false;
}
I try to avoid casts whenever possible, so I'd rather use the following, which also looks nicer in my opinion:
Integer.valueOf(8).equals(m.get("null"))
If only one of the arguments may be null (as is the case when you're comparing an unknown value to a constant), use equals() like this:
Integer foo = Integer.valueOf(8); // you could write Integer foo = 8; here too but I prefer to avoid autoboxing
if (foo.equals(m.get("x"))) { //will never throw an NPE because foo is never null
...
}
Note that your example isn't going to work in general because comparing non-primitive values with == only returns true if they refer to the same object instance. (Which in this case might even be true for very specific reasons but most of the time it isn't.)
To expand the accepted answer: i find myself having to check the equality of 2 Integer variables which might or might not be null.
So my solution would be:
boolean equals =
Optional.ofNullable(objectA.getNullableInteger()).equals(Optional.ofNullable(objectB.getNullableInteger());
You can use Objects.equals
int foo = 1;
Integer bar = null;
Objects.equals(foo, bar);

How to handle null string in java

I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate.
I tried all this but that didn't work.
String COMPLETEDATE;
COMPLETEDATE = country[23];
if(country[23] == null && country[23].length() == 0)
{
// ...
}
if (COMPLETEDATE.equals("null"))
{
// ...
}
if(COMPLETEDATE== null)
{
// ...
}
if(COMPLETEDATE == null || COMPLETEDATE.equals("null"))
{
// ...
}
For starters...the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:
if("constantString".equals(COMPLETEDDATE)) {
// logic
}
But in general, your approach isn't correct.
The first one, as I commented, will always generate a NullPointerException is it's evaluated past country[23] == null. If it's null, it doesn't have a .length property. You probably meant to call country[23] != null instead.
The second approach only compares it against the literal string "null", which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail - in that case, you would rectify it as I described above.
Your third approach is correct in the sense that it's the only thing checking against null. Typically though, you would want to do some logic if the object you wanted wasn't null.
Your fourth approach is correct by accident; if COMPLETEDDATE is actually null, the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal "null".
To check null string you can use Optional in Java 8 as below:
import Optional
import java.util.Optional;
import it as above
String str= null;
Optional<String> str2 = Optional.ofNullable(str);
then use isPresent() , it will return false if str2 contains NULL otherwise true
if(str2.isPresent())
{
//If No NULL
}
else
{
//If NULL
}
reference: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
It is not entirely clear what you are asking, but to check if a String variable is null, use the following statement.
if(myString==null)
This checks whether the object reference is null.
The following statement, which you have written is incorrect for two reasons.
if (COMPLETEDATE.equals("null"))
{
// ...
}
1. null is a keyword in Java, "null" is just a string of text.
2. .equals() checks to see if two objects are equal according to the given method's definition of equality. Null checks should always be made using the == comparison operator, as it checks reference equality.
If a variable is null, you cannot dereference it.
That means you can not invoke methods on it.
So... The following if statement will throw a NullPointerException every time the first clause is true:
if (a == null && a.length() == 0)
In other words: if a is null, you CANNOT invoke the length method on a.

Enhanced loop and possible null value

If there is a structure, an array for example, which might be null, is it valid to use a for/in loop for this structure? For example,
String[] a = someFunction(); //some function which might return null
for (String s : a) {
//do something
}
I wonder if this code will crash or not.
No. You'll get a NullPointerException
In such circumstances I always try to return empty collections, rather than null collections. That way I don't have to worry about iterating without a prior null check (you could argue this is a NullObject pattern)
Make someFunction() return an empty array if possible.
Otherwise, yeah. You'll get a NullPointerException
I wonder if this code will crash or not.
Yes. It might crash.
Note that if you return an empty collection, this might ruin your logic. You have to be sure that you don't do unexpected things when you didn't return a non-null value.
I would simply put an if that checks if the value returned from someFunction() is null:
if(a != null) {
for (String s : a) {
//...
}
}

Categories