list的contains是从头开始进行比较,而Map.containsKey则是先通过Hash值得多对应的链表,在链表内进行比较,效率显然高于list。
//源码
public int indexOf(Object o) {
//不管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]))
return i;
}
return -1;
}
//源码
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//进行hash值的比较
//只有一个结点
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//该hash值下有多个结点,判读是二叉树还是链表
if ((e = first.next) != null) {
//二叉树的比较方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
1 、map是一个key和value的键值对的集合。有key和value键值对,就会有判断是否有key。这方法就是containsKey方法。
如:
if(map.containsKey("name")){
value=map.get("name").toString();
System.out.println("找到了name的值:"+value);
}
map中的containsKey(key)方法是判断该key在map中是否有key存在。如果存在则返回true。如果不存在则返回false。
2、Contains()
用法:一个字符串中是否包含另外一个字符串
public static void main(String[] args) {
String str1="abcdefg";
String str2="def";
boolean res = str1.contains(str2);
if (res){
System.out.println("包括");
}else {
System.out.println("不包含");
}
}
注意:判断一个字符串是不是在另一个字符串中包含着,前提条件是你所判断的字符串在另一个字符串中是紧挨着的 例如: “abcdefgh”.contains(“def”) 该结果返回值为true, 如果“abcdefgh”.contains(“df”) 此时返回结果是false