DESKTOP-4LGG1I2_20200907-周拉才让

问题

1、手写集合方法中的remove方法问题

​ 删除方法如下

public Object remove( int index ) {
        if( index < 0 || index > counter ) {
            throw new IndexOutOfBoundsException( "被删除元素的索引只能是 [ 0 , " + counter + "]"  );
        }
        Object old = elements[ index ];
        System.arraycopy( elements ,  index + 1 , elements , index , counter - index );
        counter-- ;
        return old ;
    }
public void remove( Object o ) {
        int index = this.indexOf( o );
        if( index != -1 ) {
            this.remove( index );
        }
    }

​ 我们都知道第一个方法是通过传入数组的索引来删除相对应的索引的元素。

​ 而第二个方法是通过传入元素,找到元素相对应的索引,然后调用第一个方法删除。

那么实现如下代码就会出现问题

Container c = new Container( 2 );
        
        c.add( 1000 );
        c.add( 800 );
        c.add( true );
        c.add( '\u0041' );
        c.add( 3.14 );
        
        System.out.println( c );
        
        System.out.println( "- - - - - - - - - - - -" );
        
        c.remove(1000)//800相同
        c.remove('\u0041');
        System.out.println( c );
        
    }

​ 1、当想删除1000这个元素或者是200这个元素时,若不使用索引,将值传进去,默认就会调用第一个方法从而导致异常抛出。

​ 2、当想删除char类型的A时,将值传入进去,元素自动转换为int类型进而调用第一个方法,导致异常的抛出。

吐槽