通过将Array转换为List将元素添加到Array,添加元素并再次将其转换回来

时间:2013-01-13 15:52:22

标签: java arrays list

我需要将en int元素添加到数组中。

我考虑过将数组转换为arrayList,添加int,然后再将arrayList转换为数组。

正如所料,我完全失败了。

aGrades是一个数组,lGrades是一个ArrayList

// add one grade from 1-5
    public void enter (int grade){
    ArrayList<Integer> lGrades = new ArrayList<Integer>(Arrays.asList(aGrades));
    lGrades.add(grade);
    aGrades = listArray.toArray(lGrades);
  }

现在的错误是:

Histo.java:28: error: no suitable constructor found for ArrayList(List<int[]>)
    ArrayList<Integer> lGrades = new ArrayList<Integer>(Arrays.asList(aGrades));
                                 ^
constructor ArrayList.ArrayList(Collection<? extends Integer>) is not applicable
  (actual argument List<int[]> cannot be converted to Collection<? extends Integer> by method invocation conversion)
constructor ArrayList.ArrayList() is not applicable
  (actual and formal argument lists differ in length)
constructor ArrayList.ArrayList(int) is not applicable
  (actual argument List<int[]> cannot be converted to int by method invocation conversion)
Histo.java:30: error: incompatible types
    aGrades = lGrades.toArray(new Integer[lGrades.size()]);
                             ^
  required: int[]
  found:    Integer[]

这可能是一个完整的混乱,但我已经搜索了很多关于这个的线索,现在我很困惑。

非常感谢!

4 个答案:

答案 0 :(得分:0)

如果您的问题是编译时错误,则它位于以下行:

aGrades = listArray.toArray(lGrades);

只需替换为:

aGrades = lGrades.toArray(new Integer[lGrades.size()]);

虽然我建议首先使用List<Integer>

答案 1 :(得分:0)

如果您需要向阵列添加元素,最好只使用和ArrayList而不是来回转换。如果由于某种原因你不想这样做,一种更有效的方法来延长你的阵列将是这样的:

int [] newAGrades = new int[aGrades.length + 1];

System.arraycopy(aGrades, 0, newAGrades, 0, aGrades.length);

newAGrades[aGrades.length] = grade;

aGrades = newAGrades;

虽然再次使用ArrayList会更好一点:

aGrades.add(grade)

答案 2 :(得分:0)

    aGrades = Arrays.copyOf(aGrades, aGrades.length + 1);
    aGrades[aGrades.length - 1] = grade;

答案 3 :(得分:0)

正如其他人所说,最好的办法是使用带有Integer对象的ArrayList。如果你想坚持使用一个int原语数组,你最好用数组管理自己调整大小。

  // add one grade from 1-5
  public void enter (int grade){
    int[] aGradesTmp = new int[aGrades.length+1];
    System.arraycopy(aGrades, 0, aGradesTmp, 0, aGrades.length);
    aGradesTmp[aGrades.length] = grade;
    aGrades = aGradesTmp;
  }

您上面所做的是内存和处理器效率低下。这种解决方法内存效率低,但在处理器上效率更高,因为System.arraycopy()是作为本机方法实现的。

最终你只想尽可能地远离数组,只需使用集合类。