Why are two AtomicIntegers never equal?

前端 未结 9 2154
日久生厌
日久生厌 2020-12-01 18:02

I stumbled across the source of AtomicInteger and realized that

new AtomicInteger(0).equals(new AtomicInteger(0))

evaluates to

9条回答
  •  被撕碎了的回忆
    2020-12-01 18:26

    On the face of it, it seems like a simple omission but it maybe it does make some sense to actually just use the idenity equals provided by Object.equals

    For instance:

    AtomicInteger a = new AtomicInteger(0)
    AtomicInteger b = new AtomicInteger(0)
    
    assert a.equals(b)
    

    seems reasonable, but b isn't really a, it is designed to be a mutable holder for a value and therefore can't really replace a in a program.

    also:

    assert a.equals(b)
    assert a.hashCode() == b.hashCode()
    

    should work but what if b's value changes in between.

    If this is the reason it's a shame it wasn't documented in the source for AtomicInteger.

    As an aside: A nice feature might also have been to allow AtomicInteger to be equal to an Integer.

    AtomicInteger a = new AtomicInteger(25);
    
    if( a.equals(25) ){
        // woot
    }
    

    trouble it would mean that in order to be reflexive in this case Integer would have to accept AtomicInteger in it's equals too.

提交回复
热议问题