Java——Java基础之set.contains()方法

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
  • 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值