1、对于ASCII字符,是的(只要该charset涵盖了ASCII编码),使用任何charset编码都不会影响equals的判断

2、对于非ASCII字符,不一定。例如同中文字符串"你好",在UTF-8编码下的String和GBK编码下的String两个equals可能返回false

参考这篇文章中的例子:http://www.cnblogs.com/qrlozte/p/3516702.html

下面给出代码验证:

    public static String convertCharset(String arg, String charsetName) {
        String result = null;
        try {
            result = new String(arg.getBytes(Charset.defaultCharset()), charsetName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(Charset.defaultCharset());
        String s1 = "ABCD"; // 尝试把s1换成中文字符
        String s2 = convertCharset(s1, "UTF-8");
        String s3 = convertCharset(s1, "GBK");
        String s4 = convertCharset(s1, "GB2312");
        System.out.println(
                (s1.equals(s2)) + ", " +
                (s1.equals(s3)) + ", " +
                (s1.equals(s4)) + ", " +
                (s2.equals(s3)) + ", " +
                (s2.equals(s4)) + ", " +
                (s3.equals(s4))
        );
        System.out.println(s1 + ", " + s2 + ", " + s3 + ", " + s4);
    }

我的机器上的运行结果

  当s1=="ABCD"时:

  GBK

  true, true, true, true, true, true
  ABCD, ABCD, ABCD, ABCD

  当s1=="你好"时:

  GBK
  false, true, true, false, false, true
  你好, ???, 你好, 你好

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-06-16
猜你喜欢
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-05-24
  • 2021-04-21
  • 2021-07-07
相关资源
相似解决方案