删除ArrayList中的所有奇数

时间:2017-03-28 18:00:39

标签: java arraylist

我已经编写了代码来删除ArrayList中的所有奇数。

import java.util.*;

public class Odd {
    public static void main (String [] args) {
        ArrayList <Integer> mylist = new ArrayList<>(Arrays.asList(1, 2, 4, 6, 7));
        System.out.println(odd(mylist));
    }

    public static int odd(ArrayList<Integer> list) {
        if (list.isEmpty()) { throw new Error(); }
        int a = list.get(0);
        List<Integer> toRemove = new ArrayList<>();

        for (int si : list) {
            if (si % 2 != 0) { toRemove.add(si); }
        }

        list.removeAll(toRemove);
        return a;
    }
}

但不知怎的,结果总是1.有人指出我的错误是什么?提前谢谢你

3 个答案:

答案 0 :(得分:3)

您的代码存在两个问题:

(1)删除奇数后需要 public List<DiveSite> MasterDiveSiteList; DiveDBClass = new DBAccessClass(); Initialize(); private void Initialize() { MasterDiveSiteList = DiveDBClass.GetAllDiveSites(); } return个对象(包含整数)

(2)为了list return,您需要将方法签名从list更改为int(作为返回类型):

您可以参考以下代码并注释:

List<Integer>

答案 1 :(得分:1)

检查此行:

Warning: org.webrtc.voiceengine.WebRtcAudioTrack: can't find referenced method 'int getBufferCapacityInFrames()' in library class android.media.AudioTrack
Warning: org.webrtc.voiceengine.WebRtcAudioTrack: can't find referenced method 'int getUnderrunCount()' in library class android.media.AudioTrack


Warning: there were 2 unresolved references to library class members.
         You probably need to update the library versions.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)

Warning: Exception while processing task java.io.IOException: Please correct the above warnings first.
:myapp:transformClassesAndResourcesWithProguardForRelease FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':myapp:transformClassesAndResourcesWithProguardForRelease'.
> Job failed, see logs for details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

您只读取列表的第一个元素,即1,而不是通过它迭代。

使用迭代器(例如int a=list.get(0); )或常规for each循环(使用for中的项目计数)。

答案 2 :(得分:0)

正如其他人所指出的那样,问题是你要归还这个:

int a = list.get(0);

因此,您总是总是获取列表中的第一项,无论您在检索它后如何处理它。

完全摆脱a并返回list将解决该问题。