gpt4 book ai didi

java - java中如何不使用sublist方法获取子列表

转载 作者:行者123 更新时间:2023-11-30 05:09:44 25 4
gpt4 key购买 nike

这就是我现在拥有的:

public ArrayList subList(int fromIndex, int toIndex){
ArrayList a = new ArrayList();
for (int i=fromIndex;i<toIndex;i++) {
a.add(stuff[i]); //stuff is a array of strings
}
return list;
}

但是是否可以在不创建新数组的情况下返回子列表?我被限制使用 Array/ArrayList 类中的任何方法。

最佳答案

如果您希望具有与 Java subList 方法相同的行为,您需要保留指向原始列表的指针,并使用偏移量和长度来索引原始列表。

这里开始展示 get 方法的实现。

public class SubList extends AbstractList {
private final List original;
private final int from;
private final int to;
public SubList(List original, int from, int to) {
this.original = original;
this.from = from;
this.to = to;
}

public Object get(int i) {
if (i < 0 || i > to - from) {
throw new IllegalArguementException();
}

return original.get(from + i);
}
}

public static List subList(List original, int from, int to) {
return new SubList(original, from, to);
}

关于java - java中如何不使用sublist方法获取子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3861104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com