Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Empty Array as opposed to Null Array

 
Thomas Paul Bigbee
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm used to using
if (thisString != null && thisString.length() > 0)

I'm getting back an empty array (from within a serialized object over Sockets), my question is this - how do I check for an empty array?

Example...

public static void main(String[] args) {
String[][] x = new String[0][0];
if ( x == null ) {
System.out.println("x is null");
} else {
System.out.println(x[0]);
// Crash and burn - null pointer exception
}
}
Thanks in advance
Tom
 
Henrique Boreg
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x[0] does not contain a String object, it contains another array since this is a 2D array..to access a String object, you would have to access it using:


By the way, your code actually gives me an ArrayOutOfBoundsException, since the array is set to null, you could solve it by adding at least one element to it: String[][] x = new String[1][1];
[ August 20, 2005: Message edited by: Henrique Boreg ]
 
Pauline McNamara
Sheriff
Posts: 4012
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Thomas,

It's late at night here, so take this with a grain of salt...

I tried out your code and got an ArrayIndexOutOfBoundsException, not a NullPointerException.

Would something like this work for you?




That uses the array's length property.


Pauline
 
Norm Radder
Ranch Hand
Posts: 893
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two steps in creating and populating arrays.
First create an array object: String[] sa = new String[2]; // creates an array that CAN hold 2 String objects
Second add objects to it: sa[0] = "1"; // init first elem, sa[1] is still null
 
Rick O'Shay
Ranch Hand
Posts: 531
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>> how do I check for an empty array

Every array has a length property: if( array.length > 0 ) ... not empty

Using empty collections and arrays versus null references is an excellent guideline to follow. It avoids a lot of needless null or empty checks:

for(int i : array) ...

or

for( int i = 0; i < array.length; i++) ...
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rick O'Shay:

Using empty collections and arrays versus null references is an excellent guideline to follow. It avoids a lot of needless null or empty checks:


Agreed. It even has a name: the Null Object design pattern.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic