对于List.contains方法,实际上对每个对象调用一次equals方法,时间复杂度为o(n)
HashSet的contains需要对象的hashCode(根据内存地址计算)和equals都为真才会判定为true,时间复杂度为o(1)
HashMap实现了两种contains:containsKey、containsValue
containsKey:对key的hashCode和equals分别判断,时间复杂度为o(1)
containsValue :对每个value对象使用equals判断,时间复杂度为o(n)
通常在自定义类中会重写hashCode和equals方法,但是内置的类,如String
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("javaTest", 1);
String t = "oooppppjjj";
String tt = t;
String b = new String("oooppppjjj");
map.put(t, 2);
//结果均为true
System.out.println(map.containsKey(new String("javaTest")));
System.out.println(map.containsKey(b));
System.out.println(map.containsKey(tt));
System.out.println(map.containsKey("oooppppjjj"));
HashSet<String> set = new HashSet<>();
set.add("javaTest");
set.add(t);
//结果也均为true
System.out.println(set.contains(new String("javaTest")));
System.out.println(set.contains(tt));
System.out.println(set.contains(b));
System.out.println(set.contains("oooppppjjj"));
}
参考:
https://blog.csdn.net/diweikang/article/details/52474884
https://www.cnblogs.com/eco-just/p/7728741.html