一个子表如何使指的是他原来的ArrayList?

问题描述 投票:-1回答:1

我有一门功课约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();
    }
}
java arrays arraylist reference
1个回答
0
投票

一些小东西第一:

  • 坚持英语单词在你的代码。特别是在类,函数,变量等名字 - 名必须揭示的意图(没有谷歌翻译)。最好不要通过让自己做,否则得到一个坏习惯。
  • 我不是很确定你Coupe预期如何工作(是0法律分钟数或1?),但coupe.getEnd() <= tableau.size()可能失控

现在,我的建议的解决方案:

我建议您修改TableauPartiel类有startend整场除了private ArrayList<E> tableau;引用您已经有了。也许增加一个新的“拷贝构造函数”接受TableauPartiel(从中可以复制参考tableau)的实例和两个int值表明你可以使用原来的tableau的一部分(诱骗这里也看看startend值你从“sublisting”的对象)。这样,当你调用#coupe您可以检查输入数字的有效性(因为你已经这样做),只是一个参考TableauPartiel和方法PARAMS返回一个新的this对象 - startend值。添加使用这些startend以任何方法你TableauPartiel了,你应该去的好一些索引操作逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.