s=“pwwkew”
public static void lengthOfLongestSubstring(String s) {
char[] ss=s.toCharArray();
Set<String> set=new HashSet<>();
for(char c:ss){
if(set.contains(c)){
System.out.print("当前字符已存在");
}
set.add(String.valueOf(c));
}
}
遍历到第三个字符 ‘w’,set.contains( c )返回false,debug
首先是缓存机制
public static Character valueOf(char c) {
if (c <= 127) { // must cache
return CharacterCache.cache[(int)c];
}
return new Character(c);
}
Step Over
public boolean contains(Object o) {
return map.containsKey(o);
}
- this:HashSet (id=22)
- [0]:“p” (id=35)
- hash:112
- value:(id=40)
- [0]:p
- [1]:“w” (id=37)
- hash:119
- value:(id=41)
- [0]:w
- [0]:“p” (id=35)
- arg0:Character (id=36)
- value:w
Step Into
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
先比较hashCode()方法:拿到返回值119
public int hashCode() {
return Character.hashCode(value);
}
返回到getNode()方法,得到返回值null
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) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
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;
}
之前是以String类型添加到set中,不属于Character,返回false
public boolean equals(Object obj) {
if (obj instanceof Character) {
return value == ((Character)obj).charValue();
}
return false;
}
- this:Character (id=36)
- value:w
- arg0:“w” (id=37)
- hash:119
- value:(id=42)
- [0]:w
instanceof 用来测试一个对象是否为一个类的实例
boolean result = obj instanceof Class
if ((e = first.next) != null)结果为假,跳过if语句,最后返回false
返回到containsKey()方法,得到返回值false
返回到contains()方法,得到返回值false