简体   繁体   中英

Comparison for Strings constructed with uninitialized byte array cells

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?

为什么不保持简单并使用String(bytes, offset, len)构造函数构造从byte[]构建的String(bytes, offset, len)并避免包含未设置的字节:

String s2 = new String(b, 0, 8);

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