Use of array of zero length - java

For example we can construct such an array like this:
new ElementType[0];
I seen such a construct, but I don't understand why this might be useful.

An example. Say, you have a function
public String[] getFileNames(String criteria) {
to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null, or 0-sized array.
The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case).
There's a chapter on this in Effective Java, Item 27

It's easier to work with than null in many cases, where null is the obvious alternative.
Suppose you want to return an Iterable<String> containing (say) a list of relevant filenames... but there aren't any for some reason. You could return null to indicate that, but then the caller has to special-case that. Instead, if you return an empty collection, the caller can still use an enhanced for loop:
for (String file : getFiles())
So why use an empty array instead of an empty ArrayList or something similar? Arrays are a fixed size, so an empty array is effectively immutable. That means you can keep a single value and return it to whoever you like, knowing they can't possibly do anything with it. That can be very useful in some situations.

it is a replacement for null since you don't need to check for null before use it.
More formally it is a special case of special case design pattern (check also Null Object).
Another idiomatic use is collections toArray:
List<String> list = new ... ;
// fill the list
String[] array = list.toArray(new String[0]);

Related

Check that array is empty, but not null

I have an array of objects (Object[] array), and I want to check whether it is empty, but fail fast if it is null with NPE or any other exception.
I know that I can do the following check
array.length == 0
but e.g. in case of String or collections it is not recommended practice, IntelliJ even has inspection for that:
Reports any .size() or .length() comparisons with a 0 literal which can be replaced with a call to .isEmpty().
Is there any replacement for .isEmpty() for arrays?
There is ArrayUtils.html#isEmpty(java.lang.Object[]), but it also checks for null, while I'd like to avoid that.
Because .size() is method, its implementation is hidden. And you can't be sure that this method optimized (there's a possibility, that some collections, for example, enumerate items every time you call .size() method). That is why computing the .size() of collection could be expensive. In the same time, .isEmpty() can checks just is there at least one item in collection, and return result.
But .length is just a field. It does nothing, just returns a value. There are no calculations. This field just stores the length of array with fixed size.
I believe that .size() and .length are totally different things and in this case they can not be compared, as well as collections and arrays.
The easiest way would to be to write such a method yourself. It would be fairly trivial. Something like the following
public boolean isArrayEmpty(Object[] array) {
if (array == null) {
//Throw nullpointer exception
//An easy of method of doing this would be accessing any array field (for example: array.length)
}
return (ArrayUtils.isEmpty(array));
}
That being said, there's very little reason why array.length == 0 would be harmful. It's the simplest, cleanest way to do this and does exactly what you want. Most likely part of the reason for ArrayUtils.isEmpty is to allow easy testing of whether or not a array is empty or null, a relatively common need, but you don't want to do that.

Using Java 8 Optional for List of String as output

I want to use Optional for a method which returns a List
Lets say the function is
public Output getListOfSomething() {
// In some cases there is nothing to return and hence it makes sense to have return
// type as Optional here
}
Hence the function looks like :
public Optional<List<String>> getListOfSomething() {
// return something only when there is some valid list
}
Now I want to do something if the list is present so something like :
Optional<List<String>> listOfSomething = getListOfSomething();
int size = 0;
listOfSomething.ifPresent(size = listOfSomething.get().size());
I am new to Optional and have gone through the articles about Optional and it seems like this should work however am getting syntax error in my IDE :
method ifPresent is not applicable for the arguments (void).
I wanted to get some help from developers who might be more fluent with lamdas in java 8.
It's important to think about the Semantics here.
Your method could return a List, or "no list".
If it returns a List, it could return an Empty list.
You should ask, "is there a semantic reason to distinguish between an Empty List, and No List?" Sometimes there is a good design reason to make the difference, but it is rare. Think long and hard before deciding that Empty and Null are different in your case. Part of the reason to avoid No List, is that it reduces "special cases" that the client code has to consider. For example, if they have to do something for every item returned, but you could also return null, they have to do a special check for null before going into a for each loop. A for each does nothing if the list is empty.
If a "No List" is distinct from an "Empty List" in your problem domain, then it is sometimes useful to return wrapper class that helps client code distinguish between those conditions, and handle them appropriately. Optional is one such generic class, but your domain may call for something more specific (even if it mimics the functionality of Optional, it might have better semantic definition).
The true functional-programming way is the following:
size = listOfSomething.map(List::size).orElse(0);
But it would be much better to return an empty List instead of Optional.
ifPresent requires a Consumer interface to work. You could do the following:
Optional<List<String>> listOfSomething = getListOfSomething();
Integer[] size = {0};
listOfSomething.ifPresent(list -> size[0]=list.size())
But as stated by Tagir Valeev it would be better to do:
size = listOfSomething.map(List::size).orElse(0);
And it would also be better to return an empty List or even a Stream maybe.

When to return empty collections and when not too?

This question regards to the function public List inorderTraversal ().
Assume a case the root is null, the returned List is empty, ie size = 0. I am confused now since this is same as Collections.emptyList(). When should we use Collections.emptyList ? Is this inorderTraversal right place to use it instead of list with size 0 ?
public static void main(String[] args) {
List l = Collections.emptyList();
l.clear(); // No NPE
List p = null;
p.clear(); // NPE
}
So, prefer returning emptyList rather than returning null..
Collections.emptyList is a very useful means of storing a reference to an empty list (which I guess is kind of obvious).
The benefit of using it is that it's only going to occupy the memory required for a single list. Using it saves you the memory that you would use if you had multiple empty lists lying around. Also, as it's static, this List instance will always exist, whether you use it once, a thousand times or not at all.
You should use it when you wish to return a "static" list containing no objects. I use the term "static" here to indicate that the list is empty and will not be populated by any means. For example, if you have a data-access object and do a database-retrieval that yields no objects then your accessor should return a Collections#emptyList
However, if you have a list that is being used dynamically (and becomes empty as part of this), such as to back a data-structure like your own List implementation, then you should not use it as you need to keep a reference to the active list.
Additionally, if (as you should) you return defensive copies of internal arrays, then you will be able to use Collections#emptyList for when the internal list is empty.
I would return an empty collection whenever it makes sense to do so. If you need to distinguish between an empty collection and "uninitialised" or some null state, then you can return null.
You can check the size of a resulting List just before return. If the size is 0, you can return Collections.emptyList(), so your empty ArrayList will become orphaned, and will be garbage collected.
Empty lists IMO a preferable to null, since they cat prevent NullPointerException
Put simply: yes. This way, if root is null you can avoid creating ArrayList (and consuming memory unnecessarily) .
Although this is not what you ask about, but generally returning empty collection is preferred over returning null - it prevents many NPEs.
Please note that Collections.emptyList() returns an immutable list, which means that adding to it, or removing from it will fail.
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#emptyList()

Best way to check collections not null & null conditions

we use collections like ArrayList,hashmap & many more.
Number of times we have check condition like whether list is null or not.
We have many ways to chek whether our collection is null or not.
Different ways.
1. if(list==null)
2. if(list.size()==0)
3. if(list.isEmpty())
Also sometimes we also need to check whether list is not null , so we normally check it by these ways
1. if(list!=null)
2. if(list.size()>0)
3. if(!list.isEmpty())
Which is best condition or do we need to make some combination of
these considering performance of program execution?
Best combination would be
if(list!=null && !list.isEmpty()){
//Yeah ,do something
}
One for null check, and then any thing there or not check
1. if(list!=null)
You should make sure that is never the case!!
Read Effective Java 2nd Edition by Joshua Bloch
Item 43: Return empty arrays or collections, not nulls
[...] In summary, there is no reason ever to return null from an array- or
collection-valued method instead of returning an empty array or
collection. The null-return idiom is likely a holdover from the C
programming language, in which array lengths are returned separately
from actual arrays. In C, there is no advantage to allocating an array
if zero is returned as the length.
In short, let your methods return Collections.emptyList() instead of null and you've got one thing less to worry about.
2. if(list.size()>0)
3. if(!list.isEmpty())
That depends. For a simple collection such as ArrayList, they are equivalent. But what if your Collection is actually a live view of a Database query? Calling size() might me a very expensive operation, whereas isEmpty() will always be O(1). I'd say use isEmpty().
Also see Jon Skeet's answer here: https://stackoverflow.com/a/11152624/342852
In Java8 you can use Optional to handle null cases properly. For example, both lists animalsNull and animalWithNullElements would be properly handled by the function filterList:
List<String> animalsNull = null;
List<String> animalWithNullElements = new ArrayList<String>();
animalWithNullElements.add(0, null);
animalWithNullElements.add(1, "Guybrush Threepwood");
animalWithNullElements.add(2, null);
private static List<String> filterList(List<String> animals) {
return Optional.ofNullable(animals)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
It really depends on what you want to do. If you want to be sure that a list exist AND has some elements then you would use
if (list != null && !list.isEmpty())
If I may give some advice, while returning collections, return by default an empty collection. That way you will avoid nulls.
Number of times we have check condition like whether list is null or not.
For a start, a null collection and an empty collection are different things. If you need to test if a collection is null you need a different test to if you are trying to test if the collection is empty.
Secondly, if a collection could be either null or empty (and they "mean" the same thing, per your application design) then you have a problem in your design. You should most likely represent ... whatever it is you are trying to represent ... one way, and not either / both ways.
Thirdly, it is generally best to use an empty collection rather than a null, because you can treat an empty and non-empty collection uniformly. By contrast, a null always needs to be handled as a special case. (And if you forget to handle the null case, then you've got a potential for NullPointerExceptions.)
Having said that ...
Which is best condition or do we need to make some combination of these considering performance of program execution?
If you really need to deal with the case of a null, then you've no choice but to test for null.
For isEmpty() versus size() == 0:
the two predicates should give the same answer (unless you have an infinite lazy collection ...), but
in some cases isEmpty() could be faster, at least in theory.
The latter depends on the implementation of the collection type: specifically, on whether the size() method needs to count the collection elements. (I don't think that any of the standard collection classes have this property, but that's not to say that you won't find some class that does ...)
So the optimal predicate is most likely either:
c != null && !c.isEmpty()
or
!c.isEmpty()
depending on whether you (really) need to cater for nulls.
And the obvious corollary is that your application is likely to be more efficient ... as well as simpler and more robust ... if you don't use null to represent empty collections. (If you need immutable empty collection objects, you can get them for free from methods / statics defined by the Collections class.)
There is a useful util class called CollectionUtils from Apache commons-collections bundle. With using it the code will look like:
if(CollectionUtils.isEmpty(collection))
It looks nice and under the hood it has the same invocation:
public static boolean isEmpty(Collection coll) {
return coll == null || coll.isEmpty();
}
null means list is initialized with null. null list size or isEmpty will throw NullPointerException. But, not null list can be empty or size==0
(list!=null) != (list.size()==0)
size==0 and isEmpty is equivalent.
(list.size()==0) == list.isEmpty()
There can be multiple approaches to handle this:
1: If code makes sure that collection cannot be null by initializing it either in constructor or as field initializaiton then caller need not to ideally check for null everywhere. Only isEmpty check should suffice:
private List<Integer> numbers = new ArrayList<Integer>(); //or in constructor
// caller can then safely use
if(numbers.isEmpty)
2: Alternatively write a utility method to have null and empty check, no need for size check as it already happens inside isEmpty call. Use this utility method elsewhere in code.
public static boolean empty(Collection<?> col) {
return col == null || col.isEmpty();
}
It depends on your program structure. For example, I have a helper class called ArrayUtils, in which I have an API that looks like this:
public static <E> boolean isEmpty(final Collection<E> collection)
{
return collection == null || collection.isEmpty();
}
I use this one when I know that I may get a null list, but when I'm absolutely sure it's not null, I use only if ( collection.isEmpty ). Improves code readability, too.
collection.size() > 1 is redundant, because you have the other APIs at your disposal.
If it you are owner of the codebase, I would avoid using such logic at all.
Instead try to follow the model when your collection supplier can't return null but has a reference to Collections.emptyXXX or just regular empty container empty.
You can do it with two predicates as below :
public static final Predicate<String> NULL_OR_EMPTY = (in) -> null == in || "".equals(in);
public static final Predicate<List<String>> STRING_LIST_NULL_OR_EMPTY = (strList) -> strList.stream().filter(NULL_OR_EMPTY).collect(Collectors.toList()).size() > 0;

How do I create a array of LinkedLists and initialize all of them to an empty string?

I am trying to create an string array of linked lists in java. Then initialize everything inside the array to an empty string. Currently, they are all initialized with null because of the constructor. This causes a NullPointerException when I use an equals() method on the contents of the array. So I want to initialize them all to an empty string instead. How would I do this?
private LinkedList<String>[] table;
public Hashtable (int capacity, String hashFn) {
table = new LinkedList[capacity]
hashFn = hashFn;
}
I think you'll need to loop over and set each item to an empty string, like this...
private LinkedList<String>[] table;
public Hashtable (int capacity, String hashFn) {
table = new LinkedList[capacity];
String emptyString = "";
for (int i=0;i<capacity,i++){
table.add(emptyString);
}
}
I've never tried to do what you want to do, but I couldn't find any quick method to do it.
Of course, if you make it a String[] array rather than a LinkedList<String>[] array, you can simply call java.util.Arrays.fill(array,"");
If I understand your question correctly then in my opinion the better thing to do would be to use .equals() like following to avoid NPE, if you want to compare String from your LinkedList with any given String:
if("givenString".equals(strObjFromLinkedList)) {
//Do what you want
}
The direct answer is that the Collections class provides an nCopies method that you could use something like this:
List<String> l = new LinkedList<String>(Collections.nCopies(capacity, ""));
to avoid writing an explicit for loop. A for loop would be more efficient though.
But what I really want to say is that LinkedList is a BAD choice for implementing the primary hash table. Operations like get(int) and set(int, T) are O(N) for a linked list. You should be using an ArrayList<String>, or better still a String[]. These have O(1) operations for getting and setting an element. On top of that, they use significantly less memory.
In addition, you would be better of doing an explicit test for null than filling with empty strings. In reality, the JVM is likely to perform that null test behind the seens anyway. By doing it yourself, you 1) avoid the comparison with an empty string, and 2) save on the initialization time.
There is more than one way to fix an NPE problem ...

Categories