请问如何新定义 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) {
rangeCheck(index);
super.removeRange(index+1, size()-1);
}
}
[其他解释]
略微不太一样,前者一般来说是要修改对象自身,你的招数是生成一个新的对象。
[其他解释]
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,这段代码有问题哎。帮我改一下?
十分感谢!
[其他解释]
index >= size()) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
}
super.removeRange(index + 1, size());
}
}
[其他解释]
ldh911,太感谢了!
[其他解释]
你查一下API文档就行了:
removeRange
protected void removeRange(int fromIndex,
int toIndex)移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。向左移动所有后续元素(减小其索引)。此调用将列表缩短了 (toIndex - fromIndex) 个元素。(如果 toIndex==fromIndex,则此操作无效。)
覆盖:
类 AbstractList<E> 中的 removeRange
参数:
fromIndex - 要移除的首个元素的索引
toIndex - 最后一个要移除的元素后面那个元素的索引
抛出:
IndexOutOfBoundsException - 如果 fromIndex 或 toIndex 超出范围 (fromIndex < 0
[其他解释]
toIndex > size()
[其他解释]
toIndex < fromIndex)
------其他解决方案--------------------
哦,好的。你能顺便给个 API文档的下载链接么?
还有
如果想把这个静态内部类改成非静态内部类,那代码应该怎么写呢?