首页 > 解决方案 > 如何做一个子列表引用他原来的ArrayList?

问题描述

我有一个关于 ArrayList 和 Generics 类型的作业要在 java 中完成。

我有 2 节课:-> CoupeDeA -> TableauPartiel

CoupeDeA 只是一个从哪里到哪里切割阵列的描述器。(它只包含两个私有整数变量“begin”和“end”)

TableauPartiel 是 ArrayList 所在的类。

我的问题是我需要在 TableauPartiel 中创建一个方法,如下所示:

public TableauPartiel<E> coupe(CoupeDeA coupe)

并且返回的 TableauPartiel 需要是我的初始 TableauPartiel 的引用。例子 :

Integer[] arr = {8,7,6,5};
TableauPartiel<E> tab = new TableauPartiel<>(arr);

TableauPartiel<E> tab2 = tab.coupe(1,3);
tab2.set(1,45);

此代码应该在我的 tab2 的索引 1 处设置 45,同时在索引 2 处设置 45。

但是我尝试了很多不同的方法,我设法得到了子列表,但它没有指向我原来的 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 的子列表?

我使用 subList 方法找到了我的代码的解决方案,并将我的 ArrayList 的签名切换为 List,但我的老师不希望我们最终使用 subList。这是我使用 subList 方法的代码:

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();
    }
}

标签: javaarraysarraylistreference

解决方案


先说几件小事:

  • 坚持在你的代码中使用英文单词。特别是在类、函数、变量等的名称中 - 名称必须表明意图(没有谷歌翻译)。最好不要让自己做其他事情来养成坏习惯。
  • 我不太确定您Coupe的预期工作方式(是0合法的最小数字还是1?)但coupe.getEnd() <= tableau.size()可能会失控

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

我建议你修改你的TableauPartiel类,除了你已经拥有的引用之外,start还有end整数字段。private ArrayList<E> tableau;也许添加一个新的“复制构造函数”,接受一个实例 TableauPartiel(您可以从中复制引用tableau)和两个int值,指示您可以使用原始的哪一部分tableau(这里的技巧是还要查看对象的值startend子列表'从)。这样,当您调用时,#coupe您可以检查输入数字的有效性(就像您已经做的那样)并简单地返回一个新TableauPartiel对象,其中包含对this方法参数startend值的引用。start使用这些以及end您的任何方法添加一些索引操作逻辑TableauPartiel有,你应该好好去。


推荐阅读