0

我需要将 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

4 回答 4

0

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

aGrades = listArray.toArray(lGrades);

只需替换为:

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

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

于 2013-01-13T16:04:40.123 回答
0

If you need to add elements to your array, you are probably better off just using and ArrayList instead of converting back and forth. If for some reason you don't want to do that though, a more efficient way to lengthen your array would be something like this:

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

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

newAGrades[aGrades.length] = grade;

aGrades = newAGrades;

Although, again, just using an ArrayList would be a far better idea:

aGrades.add(grade)
于 2013-01-13T16:05:11.183 回答
0

try

    aGrades = Arrays.copyOf(aGrades, aGrades.length + 1);
    aGrades[aGrades.length - 1] = grade;
于 2013-01-13T16:09:14.277 回答
0

As others have stated, your best bet is to use an ArrayList with Integer objects. If you want to stick with an array of int primitives, you'd be better off managing the resizing yourself with the arrays.

  // 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;
  }

What you are doing above is memory and processor inefficient. This workaround is memory inefficient, but more efficient on the processor since System.arraycopy() is implemented as a native method.

Ultimately you just want to stay away from arrays whenever you can and just use the collection classes.

于 2013-01-13T22:32:19.513 回答