Why Does Java Allow Arrays of Size 0

Why does Java allow arrays of size 0?

It signifies that it is empty. I.e. you can loop over it as if it had items and have no result occur:

for(int k = 0; k < strings.length; k++){
// something
}

Thereby avoiding the need to check. If the array in question were null, an exception would occur, but in this case it just does nothing, which may be appropriate.

Use of Array of length 0?

We can return an empty array instead of null from a method, this is called Null object design pattern. Consider the following code

    Person[] res = find(name);
for(String e : res) {
System.out.println(e);
}

if find() does not find anyone it returns an empty array. If find returned null then code would need to treat it as a special case.

We should keep in mind that empty array is immutable so it is logical to use a singleton instead of creating it each time

private static final Person[] NULL = new Person[0];

Person[] find(String name) {
...
if (notFound) {
return NULL;
}
...

Why do arrays in Java need to have a pre-defined length when Objects don't?

My question is why does a pointer to an array need to know how big the array is beforehand, when a pointer to any other object doesn't?

It doesn't. Here, this runs perfectly fine:

String[] x = new String[10];
x = new String[15];

The whole 'needs to know in advance how large it is' refers only to the ARRAY OBJECT. As in, new int[10] goes to the heap, which is like a giant beach, and creates a new treasure chest out of thin air, big enough to hold exactly 10 ints (Which, being primitives, are like coins in this example). It then buries it in the sand, lost forever. Hence why new int[10]; all by its lonesome is quite useless.

When you write int[] arr = new int[10];, you still do that, but you now also make a treasure map. X marks the spot. 'arr' is this map. It is NOT AN INT ARRAY. It is a map to an int array. In java, both [] and . are 'follow the map, dig down, and open er up'.

arr[5] = 10; means: Follow your arr map, dig down, open up the chest you find there, and you'll see it has room for precisely 10 little pouches, each pouch large enough to hold one coin. Take the 6th pouch. Remove whatever was there, put a 10ct coin in.

It's not the map that needs to know how large the chest is that the map leads to. It's the chest itself. And this is true for objects as well, it is not possible in java to make a treasure chest that can arbitrarily resize itself.

So how does ArrayList work?

Maps-in-boxes.

ArrayList has, internally, a field of type Object[]. That field doesn't hold an object array. It can't. It holds a map to an object array: It's a reference.

So, what happens when you make a new arraylist? It is a treasure chest, fixed size, with room for exactly 2 things:

  1. A map to an 'object array' treasure chest (which it will also make, with room for 10 maps, and buries it in the sand, and stores the map to this chest-of-maps inside itself.
  2. A coinpouch. The coin inside represents how many objects the list actually contains. The map to the treasure it has leads to a treasure with room for 10 maps, but this coin (value: 0) says that so far, none of those maps go anywhere.

If you then run list.add("foo"), what that does is complicated:

  1. "foo" is an object (i.e. treasure), so "foo" as an expression resolves to be a map to "foo". It then takes your list treasuremap, follows it, digs down, opens the box, and you yell 'oi! ADD THIS!', handing it a copy of your treasuremap to the "foo" treasure. What the box then does with this is opaque to you - that's the point of OO.
  2. But let's dig into the sources of arraylist: What it will do, is query its treasuremap to the object array (which is private, you can't get to it, it's in a hidden compartment that only the djinn that lives in the treasure chest can open), follows it, digs down, and goes to the first slot (why? Because the 'size coin' in the coinpouch is currently at 0). It takes the map-to-nowhere that is there, tosses it out, makes a copy of your map to the "foo" treasure, and puts the copy in there. It then replaces its coin in the coin pouch with a penny, to indicate it is now size 1.
  3. If you add an 11th element, the ArrayList djinn goes out to the other treasure, notices there is no room, and goes: Well, dang. Okay. It then conjures up an entirely new treasure chest that can hold 15 treasure maps, it copies over the 10 maps in the old treasure, moves them to the new treasurechest, adds the copy of the map of the thing you added as 11th, then goes back to its own chest, rips out the map to the real treasure and replaces it to a map of the newly made treasure (With 15 slots), and puts an 11ct coin in the pouch.
  4. The old treasure chest remains exactly where it is. If nobody has any maps to this (and nobody does), eventually, the beachcomber finds it, gets rid of it (that'd be the garbage collector).

Thus, ALL treasure chests are fixed size, but by replacing maps with new maps and conjuring up new treasure chests, you can nevertheless make it look like ArrayList is capable of shrinking and growing.

So why don't arrays allow it? Because that shrinking and growing stuff is complicated and arrays expose low-level functionality. Don't use arrays, use Lists.

Declare an array in java without size

There is a NullPointerException because you declared but never initialized the array.

You can dynamically declare an array as shown below.

  int size = 5; // or anyother value you want
int[] array = new int[size];

Or you use a list. Which allows to dynamically change the size. E.g:

  List<Integer> list = new ArrayList<>();
list.add(5); //adds number 5 to the list
int number = list.get(0); // Returns Element which is located at position 0 (so in this example in number will be "5");

zero length arrays

If you have a function that takes an array, and you want to give it an array with nothing in it, you pass an zero-length array.

If you read an array from an external source, and it happens to not have any items, you'll get an zero-length array.

Array of zero length in java

What does ic point to, if it is not null?

It points an empty array of zero capacity. Arrays are reference types and memory space is allocated for them like any other reference type.

Use of array of zero length

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



Related Topics



Leave a reply



Submit