Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to check how many array elements are set in function  RSS feed

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all
I have simple function that get as paramets object[] some thing like that :
Object[] params = new Object[2];
params[0] = 22;
params[1] = "blah";

myFunc(params)

now in the function it self , how can I know if I know for sure that the maximum my array will contain 2 elements but minimum 0
what is the best way to check if the elements are set
I tried to do :

if(params[0] !=null ) {
�do something �..
}

but it gave me error
 
Chetan Raju
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code will not compile as

params[0] = 22;

will not compile.
 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok so "22"
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try your "(if param[0] == null)" bits.
Your method cannot ensure that two valid non-null parameters are passed. That is not the receiving method's responsibility, but the calling method's. Try this sort of thing:-And as Cheetan Raju has told you, 22 is not an object, but a primitive datum.

Because NullPointer is an unchecked Exception, you cannot force the calling method to include a try-catch block. You could use IllegalArgumentException instead. That is still unchecked.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chetan Raju:
The code will not compile as

params[0] = 22;

will not compile.

That's not always true; it will compile without problems if you're using Java 5.0, because of autoboxing.

It will not compile on Java 1.4 or older.
 
Amit Batra
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im not quite sure what it is youre trying to do exactly but why dont you try the length field of array object. like System.out.println(params.length);
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!