在項目中需要實現一個功能,獲取數據庫表的所有列,比如user表有 [name,age,height]三個字段,在插入insert之前需要判斷插入的列是否在表的列字段中,例如需要插入的數據為
{ name:"機哥", age:26, Height:"60kg", salary:"100塊"} ,插入之前比較,發現salary不在表中,把salary剔除。然后發現Height也被剔除了,因為不在列中。
jdk庫沒有現成的方法(最接近的是contains方法),自己實現了一個,如下:
public static void main(String[] args) { String orignal = "Height"; String[] arry = {"name","age","height"}; if(listContains(Arrays.asList(arry), orignal)){ System.out.printf("success"); } } private static boolean listContains(List<String> list, String ele){ for(String t:list) { if(t.equalsIgnoreCase(ele)) return true; } return false; }
原來用的是ArrayList.contains()方法,是區分大小寫的,contains內部通過indexOf(ele) > 0實現,indexOf代碼如下:
public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) //equals比較 return i; } return -1; }
然后看下equalsIngoreCase()方法實現
public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null) && (anotherString.value.length == value.length) && regionMatches(true, 0, anotherString, 0, value.length); }
首先比較對象引用相等,然后串長度一樣,最后調用regionMatches()方法
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) { char ta[] = value; int to = toffset; char pa[] = other.value; int po = ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) || (toffset > (long)value.length - len) || (ooffset > (long)other.value.length - len)) { return false; } while (len-- > 0) { char c1 = ta[to++]; char c2 = pa[po++]; if (c1 == c2) { continue; } if (ignoreCase) { // If characters don't match but case may be ignored, // try converting both characters to uppercase. // If the results match, then the comparison scan should // continue. char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) { continue; } // Unfortunately, conversion to uppercase does not work properly // for the Georgian alphabet, which has strange rules about case // conversion. So we need to make one last check before // exiting. if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) { continue; } } return false; } return true; }
regionMatches這個函數有點意思,首先是邊界檢查,如果不符合規則返回false;
之后開始字符比較,如果相等,繼續比較;如不相等並忽略大小寫,都轉成大寫比較,如果還是不相等,都轉成小寫比較,最后還是不相等,返回false。
為什么轉成大小比較不相等還不夠,還要轉成小寫的,那是因為有格魯吉亞字母(Georgian alphabet):大寫不等還不一定不等,還需要轉小寫 比如 ქართული დამწერლობა 哈哈 有意思。
