-2

Simple, I am trying to check if int[] distances is empty or not.

Why does this not work?

My Code:

int[] distances = {3,6,7,6,1,8,8,2,3,4,5,9};

    if(distances != null && !distances.isEmpty()) {
        throw new TransportException("No routes in entry");
    }
        else {

    return distances;
    }
user2863323
  • 345
  • 2
  • 3
  • 13

3 Answers3

3

There is no isEmpty() method you can call on simple arrays. Just compare its length to 0.

if (distances == null || distances.length == 0)
zbr
  • 6,860
  • 4
  • 31
  • 43
2

Java arrays don't have any method except the ones declared on java.lang.Object.

The only attribute they have is length, which is the length of the array. So you need

if (distances != null && distances.length > 0)

Read the Java tutorial about arrays. Or read an introductory Java book.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Assuming he wants to get into the body of the `if` clause when the array is either `null` or empty, this doesn't work. – zbr Dec 15 '13 at 22:07
  • Well, he just have to switch the if and else bodies. That's a bug the OP should be able to find by himself, and it's not what the question is about. – JB Nizet Dec 15 '13 at 22:09
1
if(distances != null && !distances.isEmpty()) 

condition ensures that :"Throw an exception when my array is not null and it contains some values.So it throws an exception whenever your array is NOT empty. I do not think that this is what you want.

itasyurt
  • 76
  • 4