简体   繁体   English

无法将 int 添加到整数的 ArrayList

[英]Can't add int to ArrayList of integers

I'm supposed to create a new array, which contains the first element of arrays a and b (excpet if one is empty, I must skip it).我应该创建一个新数组,其中包含数组 a 和 b 的第一个元素(如果一个为空,我必须跳过它)。 The problem is that when I try to add the int element to the ArrayList I get the error: "incompatible types: java.util.ArrayList cannot be converted to int[]" This is so annoying.. Here's the code:问题是,当我尝试将 int 元素添加到 ArrayList 时,出现错误:“不兼容的类型:java.util.ArrayList 无法转换为 int[]” 这太烦人了.. 这是代码:

public int[] front11(int[] a, int[] b) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (a.length>0 & b.length>0){
    list.add(a[0]);
    list.add(b[0]);
}
if (b.length==0 & a.length>0){
    list.add(a[0]);
}
if (b.length>0 & a.length==0){
    list.add(b[0]);
}
return list;

} }

list is not an int[] and you don't need a List here. list不是int[]并且这里不需要List Nor do you need an instance, so I'd make it static and I would do it inline (and I would also guard against null ).你也不需要一个实例,所以我会把它static ,我会内联(我也会防止null )。 Like,喜欢,

public static int[] front11(int[] a, int[] b) {
    int alen = (a != null) ? a.length : 0, blen = (b != null) ? b.length : 0;
    if (alen > 0 && blen > 0) {
        return new int[] { a[0], b[0] };
    } else if (alen > 0) {
        return new int[] { a[0] };
    } else if (blen > 0) {
        return new int[] { b[0] };
    } else {
        return new int[0];
    }
}

An ArrayList is not an array, no matter the name of the class.无论类的名称如何, ArrayList都不是数组。 It's named that way because it uses an array internally to manage the list.之所以这样命名是因为它在内部使用数组来管理列表。

Using an ArrayList is also overkill here.在这里使用ArrayList也是过分的。 You have 4 scenarios, so just code them and create the returning array as needed:您有 4 个场景,因此只需对它们进行编码并根据需要创建返回数组:

public static int[] front11(int[] a, int[] b) {
    if (a.length > 0 && b.length > 0)
        return new int[] { a[0], b[0] };
    if (a.length > 0)
        return new int[] { a[0] };
    if (b.length > 0)
        return new int[] { b[0] };
    return new int[0];
}

Convert int[] return type into ArrayList<Integer>将 int[] 返回类型转换为ArrayList<Integer>

    public ArrayList<Integer> front11(int[] a, int[] b) {
ArrayList<Integer> list = new ArrayList<Integer>();
if (a.length>0 & b.length>0){
    list.add(a[0]);
    list.add(b[0]);
}
if (b.length==0 & a.length>0){
    list.add(a[0]);
}
if (b.length>0 & a.length==0){
    list.add(b[0]);
}
return list;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM