日期:2014-05-20  浏览次数:20595 次

请问如何新定义 ArrayList方法?十分感谢!
各位达人,

我在使用 ArrayList的时候,需要新定义一个方法,要求删除 ArrayList里某个指标之后的所有的元素。

public void removeafter(int index) {
        rangeCheck(index);

        ...

    }

请问这个方法应该怎么写?

非常感谢!
------最佳解决方案--------------------
如下:

    public static void main(String[] args) {
        MyArrayList<Integer> lst = new MyArrayList<Integer>(); // 必须new你自己的实现类
        for (int i = 0; i < 10; i++) lst.add(i);
        lst.removeAfter(5);
        for (int i = 0; i < lst.size(); i++) {
            System.out.println(lst.get(i));
        }
    }

    public static class MyArrayList<E> extends ArrayList<E> { // 这个要加 static,因为你是静态方法中引用的。
        public void removeAfter(int index) {
            // super.RangeCheck(index); // 这个是private的,没法被调用
            if (index < 0 
------其他解决方案--------------------
 fromIndex >= size() 
------其他解决方案--------------------

ArrayList.subList(0, index)

删除后面的,意思不就是获取前面的。
------其他解决方案--------------------

class MyArrayList<T> extends ArrayList<T>
{
public void removeafter(int index)
{
if(index>=this.size()) //给出的索引超出范围.
{
return;
}
while(this.size()>index)
{
super.remove(index);
}
}
}

------其他解决方案--------------------
ldh911,如果想把这个静态内部类改成非静态内部类,那代码应该怎么写呢?

非常感谢!

public /*static*/ class MyArrayList<E> extends ArrayList<E> { 

------其他解决方案--------------------
这样如何?
  super.removeRange(index+1, size()-1);
------其他解决方案--------------------
public void removeafter(int index) {
        rangeCheck(index);
        super.removeRange(index+1, size()-1); 
    }


ldh911, 那这个函数放在什么地方?直接放在 ArrayList这个类里面??
------其他解决方案--------------------
ldh911,能直接给个例子么?简单的能运行的就好了
------其他解决方案--------------------
咋可能直接让你去修改Java自带的类。。。

一般这样:
public MyArrayList extends ArrayList {
    public void removeafter(int index) {