使用Map<key,value>資料結構時,如果要忽略key的大小寫敏感,可以使用TreeMap,構造函數傳入String.CASE_INSENSITIVE_ORDER比較器,它是一個忽略大小寫的Comparator對象。
使用示例如下:
Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
在mysql-connector-java的ResultSetImpl類中,就使用了大小寫不敏感的TreeMap對象來存儲字段名和值,因為MySQL中字段名是不區分大小寫的。
public void buildIndexMapping() throws SQLException {
int numFields = this.fields.length;
this.columnLabelToIndex = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
this.fullColumnNameToIndex = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
this.columnNameToIndex = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
...
一個簡單的測試用例如下:
package com.taoxi.mybatis.mysimple;
import org.junit.Test;
import java.util.TreeMap;
public class MysimpleApplicationTests {
@Test
public void testMapCaseInsensitive() {
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
treeMap.put("KEY1", 11);
treeMap.put("key2", 22);
Integer key2 = treeMap.get("Key2");
System.out.println("key2's value is " + key2.toString());
}
}
結果:
key2's value is 22