This question already has answers here:
Why does Java allow arrays of size 0?
(9 answers)
Closed 9 years ago.
char[] arrNew = new char[0];
System.out.println(arrNew.length); // length = 0
arrNew[0]='c'; // ArrayIndexOutOfBoundsException .
In the above code as you can clearly see there is no point in having an array of size 0. As far as I can see there is no practical usage of 0 size array. Can someone explain why the compiler allows creation of 0 length array. And also how is a 0 length array different from an array initialized to null? (i.e, is memory allocated to it as if it were a normal array?). I am sorry if this question seems stupid.
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;
}
...
It's best not to return null from a method that returns an array type. Always returning an array, even if the array has zero length, greatly improves the generality of algorithms. If you anticipate that your methods will return zero-length arrays frequently, you might be concerned about the performance implications of allocating many such arrays. To solve that problem, simply allocate a single array, and always return the same one, for example:
private static final int ZERO_LENGTH_ARRAY[] = new int[0];
This array is immutable (it can't be changed), and can be shared throughout the application.
So in Null Object pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour in case data is not available.
Compiler allows because that code its within the rules of the language.
And no, they are both not the same. If it were the same, you would get a NullPointerException rather than ArrayIndexOutOfBoundsException.
It can be of use, if you have a function returning reference to array, and if you have nothing to return then you might consider its better to return 0 length array than a null. If null were returned you would have to check this function for both null value, and if range is correct, if you return 0 length array - then you might only check the if range is correct - ie. in for loop.
Zero-length arrays are rarely "required," but are more often used simply to show that there is no data being passed to a method.
in java the memory allocation can be dynamic in nature. The java array enables the user to store values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure which can not be altered when required. It just occupies the memory.
Related
I come from a C#.net background and whenever I had a string I was declaring it as String.Empty
Now I am looking at a Java code from a co-worker and he has declared his strings in a method like this:
String myStr = null;
I don't like it, and even worse, he is assigning values to these strings in an "IF" block where it may or may not even qualify, and then at the end of the method he is calling a myStr.length() on them.
So my question is what is a preferred way in Java? do you think is it better to define them as String.Empty OR leave them as null and do a null check just before calling .length() on them?
In general, using null values is a bad idea, especially if they are returned from a method or passed to another method. Using the Null Object pattern is better, and in a string's case the Null Object is an empty string. By consistently avoiding nulls, the probability of getting a NullPointerException gets smaller and the code becomes more readable (this is discussed at length in Clean Code chapter 7, pages 110-112).
In Java String s = "" does not allocate any memory, because the JVM will have interned the string literal, so there isn't even a performance difference (and even if there were, it would be a premature optimization).
They both have their uses. Empty strings are in-band, i.e. can occur in the input, so they are no use as sentinels. Null is only useful as a sentinel. If you're going to append to it you should initialize it with "" of course. If you're going to immediately reassign it there's no need to provide any value at all, and you should probably combine the declaration with the reassignment. I see far too much of this:
String s = new String();
s = "some string";
All this tells me is that somebody doesn't understand the language.
thought both are applicable for different scenarios, assigning it null will be better(saves memory and less error prone) provided you later on set some string to that else you will be getting a null pointer exception.
An empty String is often a sign that you should either be using a StringBuilder if you're appending (which is a common case). A null reference is 'better' because it uses less memory and it's faster to check if a String is null compared to checking if it's empty. I would advice against using empty Strings instead of declaring them as null, though you should still check for null reference before you use it unless you're 100% sure that it would have been assigned a value at some stage.
This question already has answers here:
length and length() in Java
(8 answers)
Closed 6 years ago.
I've noticed that when doing the length of an array you write something like:
arrayone.length;
However, for such things as array lists or a string, you write a bracket on the end, such as the following for the length of the String:
stringone.length();
What is the key reason for this and how do you know when to put the brackets or now?
.length;
directly accesses a field member.
.length();
invokes a method (i.e. an accessor) to access a field member.
in the case of String, this is to be expected since it's immutable.
Arrays are handled differently than Strings or ArrayLists or anything else that can be counted in Java. An Array is pretty much a native type and it's length can never be changed after it is initialized, so there's no need for encapsulation. The length variable can be directly exposed with no side effects.
The reason why String uses a method instead of a variable is because it internally uses a char[] that it doesn't want to expose publicly (for immutability/encapsulation), so it wraps the length variable in a length() method. It's the same reason ArrayList has a size() method instead of a length variable.
The only time you'll use the variable instead of the method is with arrays. Everything else will be methods. That is, you'll use the brackets for everything except arrays.
The only true way to know when to use which one is experience. Though an IDE with autocompletion will usually help you out when you don't remember.
For the most part (not always) array.length, System.out, and System.err are the most common 3 you'll run into that are actually member access instead of method calls.
int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();
myArray.length //gives the length of the array
myString.length() //gives the length of the string
myList.size() //gives the length of the list
Its very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally a method length() was used to avoid duplication of the same information. Ultimately this is just an inconsistently that evolved that would definitely be fixed if the language were ever redesigned from the ground up. :D
The main difference is that in the A) first case its Array Type for example int[], Object[], double[], ect.. that has a public field called lenght and the B) second case is a Object String that has a function called length(), the function could of been called getLength() or something else. The array type public field length is probably a hangover from C++ way of doing things.
Array Types have the following:
The public final field length, which contains the number of
components of the array (length may be positive or zero)
The public method clone, which overrides the method of the same name
in class Object and throws no checked exceptions
All the members inherited from class Object; the only method of
Object that is not inherited is its clone method
Take a look at this, Array Types.
.length() is a method of a String class and which returns the number of characters in the string.
.length will give the number of elements stored in an array.
public class length
{
public static void main(String args[])
{
String x="test";
int a[]={1,2,3,4};
System.out.println(x.length());
System.out.println(a.length);
}
}
// output
4
4
length is a pseudo-data member reference, and only works for (small-a) arrays (ignoring classes that you may define that implement the member).
Everything else is an object of a class, and all JDK classes that have this concept define either length() or size() instance methods. (I do wish they'd been consistent and picked one or the other, but that's water over the bridge.)
Array.length is a property of that Array, similar to a variable reference.
ArrayList.size() is an actual method call to the array list object.
I get a NullPointerException at a line on which just a simple null check takes place.The line is the following:
if(routingTable[commonBitGroups][nextNumberOfOther-1]==null)
I verify that the array is not null just before this line.
commonBitGroups and nextNumberOfOther are both simple int types.
I should add that this line is part of an app that uses rmi and part of a class which extends UnicastRemoteObject and implements a RemoteInterface.I specify that because I am under the impression that a NullPointerException can occur when you deal with synchronization even if nothing is realy null (maybe when something is locked) ,and I deal with synchronization in this app.The method that contains the line though is not synchronized and nowhere in my code I try to use the array as a monitor (I only have some synchronized methods ,no smaller synchronized blocks so I nowhere choose a specific monitor explicitly).
If the following line throws an NPE:
if (routingTable[commonBitGroups][nextNumberOfOther - 1] == null)
then either routingTable is null or routingTable[commonBitGroups] is null.
You say that the array is initialized as follows:
routingTable = new NodeId [32][15];
Arrays.fill(routingTable, null);
"Well there's your problem!"
The first line gives you an array of 32 NodeId[]'s, with the elements initialized to non-null values ... arrays of size 15. (So far so good ...)
The second line sets routingTable[i] to null for all i .... Ooops!!
Delete the second line.
As #Gabe says, it's probably that routingTable[commonBitGroups] is null. Java does not have real multidimensional arrays: a 2-d array is an array of arrays (and a 3-d array is an array of arrays of arrays).
Incidentally you don't have to initialize references in an array to null in Java, that is their default value. In this case it's also your problem. You're setting the second level of array values to null. What you meant was
for (int i = 0; i < 32; i++) {
Arrays.fill(routingTable[i], null);
}
But as above, this is unnecessary. So just remove your call to Arrays.fill.
Supposing I have a function with following signature:
Foo[] getSomeFoos()
{
//return null --- option A
or
//return new Foo[0]; --- option B
}
What is the recommended practice to return the value indicating there is no elements returned? Any pros or cons for each option?
If your method GetSomeFoos() actually 'found' 0 elements, then it should return new Foo[0].
If there was some sort of error, you should throw an Exception.
The reason is because users shouldn't have to look for nulls:
for (Foo f: GetSomeFoos()) {
// do stuff
}
In the above case, if GetSomeFoos returned null, a user will have to deal with an NullPointerException. But, if you return an empty array, the code will never enter the loop, and the user will not have to deal with an exception.
Whether to return null or empty object entirely depends on the method usage. If this method is called by a client and exposed as an API then throwing exception is better , but if it is used within ur package and never used by client then returning null is ok.
Returning null is more efficient, since you avoid the overhead of creating a new array or collection object. It's true that you then have to add a null check at the point where you use the function's output, but the overhead for that (in Java and almost all languages) is negligible. I also think that checking for null is a good habit to get into, especially when dealing with third-party libraries.
The downside is that you make the code more verbose.
If you do return an empty array, you can mitigate the performance hit by re-using the same object. Create an immutable constant, and return that:
private static final String[] EMPTY = {};
Or:
private static final List<String> EMPTY =
Collections.unmodifiableList(new ArrayList<String>());
I prefer zero-size array.
It's safer(avoid NPE) and easier(no need null check).
From Effective Java (2nd ed) - 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
In Java, is there a way to truncate an array without having to make a copy of it? The common idiom is Arrays.copyOf(foo, n) (where the new array is n elements long). I don't think there is an alternative, but I'm curious as to whether there is a better approach.
An array's length in Java cannot be altered after initialization, so you're forced to make a copy with the new size. Actually, the length parameter of a Java array is declared as final, so it cannot be changed once it's set.
If you need to change an array's size, I'd use an ArrayList.
I was thinking about it some more... and just for kicks, how about something like the below.
Note: This is just a "can it be done?" intellectual exercise in Java hacking. Anybody who attempts to actually use this idea in production code will deserve all the pain that will undoubtedly follow.
public class Foo
{
private static byte[] array = new byte[10];
public static void main(String[] arg) throws Exception
{
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
Field arrayField = Foo.class.getDeclaredField("array");
long ptr = unsafe.staticFieldOffset(arrayField);
// doesn't work... there's gotta be a way though!
unsafe.reallocateMemory(ptr, 5);
System.out.println("New array size is: " + array.length);
}
}
I don't believe so. An array is allocated as a contiguous block of memory, and I can't imagine that there is any way of releasing a part of that block.
Succinctly: No, There isn't, as far as I know. A Java array is a fixed-size data-structure. The only way to "logically" resize it is create a new array and copy the wanted elements into the new array.
Instead: You could (possibly) implement a class which wraps an array into a collection and uses a "size" variable to logically reduce the length of the array without actually copying the values. This an approach has limited utility... The only case I can imagine where it's practical is when you're dealing with a huge array, which just can't be copied because of memory limitations.
Copying an array is relatively inexpensive time-wise... unless you're doing it millions of times, in which case you probably need to think up an algorithm to avoid this, and not waste your time mucking around with a "variable length array".
And of course... you could just use an ArrayList instead. Yes?