0

A follow up to one I asked long time ago, I'm trying to construct Strings from byte arrays which may not have all cells set to a specific value (cf. code below). It seems that if a String is constructed from suchlike byte array, the allocated-but-unset bytes still counts, making comparisons (using equals()) fail.

See,

public class Test{
    public static void main(String[] args){
        byte[] b = new byte[10];
        String s = "RESET ME";
        for(int i = 0; i < 8; i++){
            b[i] = (byte) s.charAt(i);
        }
        String s2 = new String(b);
        System.out.println(s.equals(s2));
    }
}

Which prints "false". Short of writing my own comparator, is there a way to compare Strings such that it does not take the unset bytes into account?

4
  • "uninitialized" byte[] cells will be 0 (so the corresponding characters in the String will be U+0000). This is not undefined behaviour in Java. Commented Jul 16, 2013 at 11:53
  • And as a general note: why do you have characters in your String that you do not care about in the first place? Get rid of those, and continue working with a sane String. Commented Jul 16, 2013 at 11:54
  • That came from a buffer data structure I was using. Basically, I was listening for transactions over a socket, but it may happen that the transaction terminates without using everything in the buffer, hence the blank cells. Commented Jul 17, 2013 at 1:59
  • in that case you usually know how much data was sent/used. Commented Jul 17, 2013 at 5:39

1 Answer 1

2

Why not keep it simple and construct the string built from the byte[] using the String(bytes, offset, len) constructor and avoid including the unset bytes at all:

String s2 = new String(b, 0, 8);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.