62,616
社区成员
发帖
与我相关
我的任务
分享
MyArrayList<Integer> List = new MyArrayList<Integer>();
这个语句写在 main函数体外面么?public /*static*/ class MyArrayList<E> extends ArrayList<E> {
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 || index >= size()) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
}
super.removeRange(index + 1, size());
}
}
import java.util.ArrayList;
public class RemoveTest {
public class MyArrayList<E> extends ArrayList<E> {
public void removeAfter(int index) {
rangeCheck(index);
super.removeRange(index + 1, size() - 1);
}
public MyArrayList() {
}
}
public static void main(String args[]) {
MyArrayList<Integer> List = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
List.add(i);
List.removeAfter(5);
for (int i = 0; i < List.size(); i++) {
System.out.println(List.get(i));
}
}
}
ldh911,这段代码有问题哎。帮我改一下?
十分感谢!
class MyArrayList<T> extends ArrayList<T>
{
public void removeafter(int index)
{
if(index>=this.size()) //给出的索引超出范围.
{
return;
}
while(this.size()>index)
{
super.remove(index);
}
}
}
ArrayList.subList(0, index)
删除后面的,意思不就是获取前面的。public MyArrayList extends ArrayList {
public void removeafter(int index) {
rangeCheck(index);
super.removeRange(index+1, size()-1);
}
}