1 String類型有一個方法:contains(),該方法是判斷字符串中是否有子字符串。如果有則返回true,如果沒有則返回false。
1 if(map_string.contains("name")){ 2 System.out.println("找到了name的key"); 3 } 4 if(map_string.contains("password")){ 5 System.out.println("找到了password的key"); 6 }
2.list.contains(o),比較list是否包含o
系統會對list中的每個元素e調用o.equals(e),方法,加入list中有n個元素,那么會調用n次o.equals(e),只要有一次o.equals(e)返回了true,那么list.contains(o)返回true,否則返回false。因此為了很好的使用contains()方法,我們需要重新定義下Student類的equals方法,根據我們的業務邏輯,如果兩個Student對象的orderId相同,那么我們認為它們代表同一條記錄 :
ArrayList的contains方法的實現:
1 public boolean contains(Object o) { 2 return indexOf(o) >= 0; 3 } 4 public int indexOf(Object o) { 5 if (o == null) { 6 for (int i = 0; i < size; i++) 7 if (elementData[i]==null) 8 return i; 9 } else { 10 for (int i = 0; i < size; i++) 11 if (o.equals(elementData[i])) 12 return i; 13 } 14 return -1; 15 }