DESKTOP-LODEUIH_20200907-罗祥

日志

问题

问题:
public boolean retainAll(Collection<?> c) {
        final int oldCounter = this.counter ;
        int z = 0;
        if( c instanceof Bag ) {
            Bag other = (Bag) c ;
        for( int i = 0 ; i < this.counter ; i++ ) {
                Object o = this.elements[ i ];
                if( !other.contains( o ) ) {
                    this.remove( o ) ;
                    z++;
                }
            }
        }
        return  (counter+z)==oldCounter;
    }

出现漏删的现象,怎么解决?

来源:课后练习
解决:
public boolean retainAll(Collection<?> c) {
        final int oldCounter = this.counter ;
        int z = 0;
        if( c instanceof Bag ) {
            Bag other = (Bag) c ;
            for( int i = 0 ; i < this.counter ; i++ ) {
                Object o = this.elements[ i ];
                if( !other.contains( o ) ) {
                    this.remove( o ) ;
                    i-- ;//
                    z++;
                }
            }
        }
        return  (counter+z)==oldCounter;
    }

当删除一个元素时,剩余元素的下标迁移,如果不加i--,则某个元素的下标前移,,i++继续向后直行,就会出现遍历不到某个元素,出现漏删的现象。

吐槽

​ 今天的代码有点多啊!