Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following variables:

byte[][] bytes;
byte[] value;

Is there a smart way to find the index of the first matching entry of value in bytes ?

value is NOT the same object as an entry in bytes, it just has the same contents.

Of course you could just do:

int idx = -1;
for(int i=0;i<bytes.length;i++) {
   if(Arrays.equals(value, bytes[i])) {
      idx = i;
      break;
   }
}
// idx is index or -1 if not found

I was just wondering if it can get even easier.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

Because you're just talking about arrays of bytes ... no.

What you have in your example code is the way to do it; you're going to have to compare them byte by byte. And more than likely that is perfectly acceptable.

About the only way to "make it easier" would be to encapsulate the byte array in an object that provided a way to compare them using a unique hashing algorithm (See: equals() and hashcode() ). Even then you would need to consider the overhead of computing the hash, and the difficulty/cost of ensuring the uniqueness in regard to the algorithm. A thought there would be making the object immutable and computing the hash at object creation if you're expecting to do many comparisons and really need that sort of optimization; it's unlikely that you do :)

share|improve this answer
 
Okay, thanks for the answer. I was just wondering because I often found one-liners to such problems before :) –  AyCe Jun 15 at 23:18
add comment

I would change the code so you didn't need a condition check.

FOUND: {
    for(int i = 0; i < bytes.length; i++) {
       if(Arrays.equals(value, bytes[i])) {
          // handle found match
          break FOUND;
       }
    }
    // can only be here if it didn't find a match
}
share|improve this answer
 
Cool, coding Java since years and didn't even know that :D –  AyCe Jun 15 at 23:19
2  
@AyCe: That's because you're not supposed to use it. ;) This is essentialy a goto. Sure, it works well if used properly, but the code can easily get messy with them. –  Patrick Jun 15 at 23:22
 
@Code-Guru That will only break the loop. This will ensure you don't run the code for "not found" if it is found. i.e. the "goto" is further than just the end of the loop. –  Peter Lawrey Jun 15 at 23:37
1  
@Patrick There is very rarely a good reason to use it, in fact this is the only one I can think of as it avoids a redundant condition check after the loop. –  Peter Lawrey Jun 15 at 23:37
 
Doh! Parse error on my part ;-( –  Code-Guru Jun 15 at 23:42
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.