简体   繁体   中英

Java get the object that is not null

I have an array with 4 objects, and only one of them is not null . I want to call a method, giving that variable as a param.

Block[] b = getIntersectingBlocks(e); // I get 4 Block variables, and only one of them is not null
// ...
Listener.myMethod(notNullBlock); // notNullBlock should be the block out of the array, that is not null

What is the fastest way of doing that, and avoiding if - else statements like this:

if (b[0] != null) {
    Listener.myMethod(b[0]);
} else if (b[2] != null) {
    Listener.myMethod(b[1]);
}
// ...

This doesn't use multiple if and will work for an arbitrary length array:

for (Block block : b)
    if (block != null)
        Listener.myMethod(block);

If more than one Block can be non-null, add a break to prevent the listener being called more than once:

for (Block block : b) {
    if (block != null) {
        Listener.myMethod(block);
        break;
    }
}

If understand your question, you could do it with a massive nested ternary (please don't do this in real code),

final Block notNullBlock = (b == null || b.length != 4) ? null :
    b[0] != null ? b[0] : b[1] != null ? b[1] : b[2] != null ? b[2] :
    b[3];

You could also use a for-each loop (but it requires an if ) -

Block notNullBlock = null;
for (Block block : b) {
  if (block != null) {
    notNullBlock = block;
    break;
  }
}

Use for each loop

for(Block bl:bArray){
   if(bl !=null)
    Listener.myMethod(b1);
}

Let say you have an array of Block as below: Block[] blocksArray = {null, null, new Block(), null};

Pass above array to this method:

    private Block provideBlock(Block[] blocksArray)   { 
        for(Block block : blocksArray) {
            block instanceof Block? return block : continue;
        }
    }

Then use returned not null block in your code as:

Block block = provideBlock(blocksArray);
Listener.myMethod(block); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM