package com.cnse.demo; /** * 比較兩個字符串相等 */ public class StringTest { public static void main(String[] args) { int checkLength = 0; String str="好人"; String in="好人"; if(str.equals(in)){ System.out.println("equals比較::"+Boolean.valueOf(str.equals(in))); } char[] strarray=str.toCharArray(); char[]inarray=in.toCharArray(); for (int i = 0; i < inarray.length; i++) { for (int j = 0; j < strarray.length; j++) { if (inarray[i] == strarray[j]) { System.out.println("charArray比較::"+Boolean.valueOf(inarray[i] == strarray[j])); System.out.println("兩個字符串相等"); System.out.println(inarray[i] +":::::in::::測試字符串::"+strarray[j]); checkLength++; break; } } } } } //java的equeals源碼分析 //考慮的比較全面 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; //使用的是i-- 把字符倒着比較 int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }