我有一门功课约ArrayList和泛型类型的java做。
我有2类: - > CoupeDeA - > TableauPartiel
CoupeDeA距离哪里到哪里的阵列被切断描述者。 (它仅包含两个私有整型变量“开始”和“结束”)
TableauPartiel就是ArrayList的是类。
我的问题是我需要TableauPartiel这样创建的方法:
public TableauPartiel<E> coupe(CoupeDeA coupe)
而TableauPartiel返回需要是我最初的Tableau部分的参考。例如:
Integer[] arr = {8,7,6,5};
TableauPartiel<E> tab = new TableauPartiel<>(arr);
TableauPartiel<E> tab2 = tab.coupe(1,3);
tab2.set(1,45);
这个代码理应组45在我的TAB2索引1,并在同一时间设定45在索引2处。
但我试过很多不同的方式和我设法让子表,但没有指向我原来的ArrayList。
例如,我想是这样的:
private ArrayList<E> tableau;
...
public TableauPartiel<E> coupe(Coupe coupe)
throws IndexOutOfBoundsException {
if (coupe.getBegin() >= 0 && coupe.getEnd() <= tableau.size()) {
TableauPartiel<E> tab = new TableauPartiel<>((E[]) new Object[coupe.getEnd()-coupe.getBegin()]);
for (int i = 0; i < coupe.getEnd()-coupe.getBegin(); ++i) {
tab.set(i, this.get(coupe.getBegin()+i));
}
return tab;
} else {
throw new IndexOutOfBoundsException();
}
}
我该怎么做才能让这指的是他原来的ArrayList的子列表?
我已经找到了解决方案,我与子列表方法的代码,并通过切换我的ArrayList中列出的签名,但是我的老师不希望我们最后使用子列表。这是我与子表方法的代码:
TableauPartiel<E> tab;
if (coupe.getDebut() >= 0 && coupe.getFin() <= taille()) {
if (coupe.getFin() == -1)
tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),taille()));
else
tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),coupe.getFin()));
return tab;
} else {
throw new IndexOutOfBoundsException();
}
}
一些小东西第一:
Coupe
预期如何工作(是0
法律分钟数或1
?),但coupe.getEnd() <= tableau.size()
可能失控现在,我的建议的解决方案:
我建议您修改TableauPartiel
类有start
和end
整场除了private ArrayList<E> tableau;
引用您已经有了。也许增加一个新的“拷贝构造函数”接受TableauPartiel
(从中可以复制参考tableau
)的实例和两个int
值表明你可以使用原来的tableau
的一部分(诱骗这里也看看start
和end
值你从“sublisting”的对象)。这样,当你调用#coupe
您可以检查输入数字的有效性(因为你已经这样做),只是一个参考TableauPartiel
和方法PARAMS返回一个新的this
对象 - start
和end
值。添加使用这些start
和end
以任何方法你TableauPartiel
了,你应该去的好一些索引操作逻辑。