Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to find if elements of an array is null

 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,

I am decalring following:

byte[] bb = new byte[512];

and want to know after some processing that if all elements of this bb byte array are null or not. Is there any way of finding the same except runnign a while loop?

regards
Arun
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No elements of this array will ever be null; only object references can be null, and a byte is not an object reference. If you want to find out if any elements are 0: yes, in general, you need to check with a loop.
 
Jon Egan
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree, I think you would need to use a loop.... but here are some really bad alternatives, just for fun:


// Could probably be improved with some Pattern matching, and could
// definitely be improved with fewer (ideally 1) invocation of
// Arrays.toString().... but what fun would that be?
((Arrays.toString(bb).indexOf(" 0,") < 0) &&
(Arrays.toString(bb).indexOf("[0,") < 0) &&
(Arrays.toString(bb).indexOf(" 0]") < 0) &&
(!Arrays.toString(bb).equals("[0]"))


// Have to clone only if you want to maintain the original ordering
Arrays.sort(bb.clone()).binarySearch((byte)0)


// hrmmm.... I bet this is looping internally anyway...
Arrays.aslist(bb).contains((byte)0)


Alright, enough foolishness. Good luck,
-- Jon
 
arun mahajan
Ranch Hand
Posts: 305
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks fo ryour reply.

I also tried this way:

String str = new String(bb);

if(str.length()<1)
System.out.println("Array is empty");

Though seems a bit inefficient

//br Arun
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic