public class Demo08 { public static void main(String[] args) { String str = "test"; boolean test = str.equals("test");//true int test1 = str.compareTo("test");//0 System.out.println(test); System.out.println(test1); str.concat("a"); System.out.println(str);//test } }
equals比较的是两个字符串的值,返回true或false
源码解析:
1.如果比较的两个字符串是同一个对象,直接返回true
2.要比较的对象是否是字符串,不是字符串,返回false,是字符串时将要比较的对象强转为String,然后比较两个字符串的长度,长度不一样返回false,长度一样的依次比较每个字符,所有字符都一样返回true,否则返回false
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
compareTo比较的是两个字符串的值,返回值为数值。如果两个字符串相同,返回0,前面的字符串大于参数中的字符串返回大于0的数值,前面的字符串小于参数中的字符串返回小于0的数值。
源码解析:
compareTo按照两个字符串的最小长度依次比较字符做减法,如果都相同,长度相减
public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; }
concat源码: public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); }