簡體   English   中英

比較 ArrayList 中的元素

[英]Compare elements from an ArrayList

我有一個小問題,我想遍歷一個列表並比較數組的兩個對象。 每個對象有 3 個元素,我使用 StringTokenizer 來去除分隔符,所以每個對象有 3 個元素。 我想知道如何制作一個方法來獲取每個對象的第三個元素並進行比較。 如果該元素小於另一個刪除該元素和它之前的 2。

我試圖用迭代器制作它們,但我不太清楚它是從 3 元素開始並將位置增加 3。

Iterator<Integer> it = lisM.iterator();
                int num;
                while (it.hasNext()){
                    num = it.next();
                    System.out.println(num);

                }

視覺示例

是 --> 如果,我把它放在圖片中是錯誤的

這僅回答了您的部分問題。 我無法完全理解這個問題,請編輯它,我可以編輯我的答案。

您不應該在 for 循環中從列表中刪除項目,因此您可以,例如,創建另一個大小相同的布爾列表除以 3,然后用真正的布爾值填充它,然后將除以 3 的位置設置為false如果您想刪除這三個項目。 然后您可以創建一個新列表,遍歷布爾列表並一次添加 3 個實際上是字符串的“對象”(感謝 @JB Nizet),每次布爾列表元素為真時。 當它為 false 時,您只是不添加元素,這樣做實際上是在刪除該元素之前的兩個元素以及該元素。

您將String轉換為int ,這不起作用您必須解析字符串。

我更正了您的一些代碼並在此處添加了布爾列表:

    ArrayList<String> lisM = new ArrayList<>();  // here I initialise the list as an array list with strings. 

    ArrayList<Boolean> booleanList = new ArrayList<>();
    for (int i = 0; i < lisM.size() / 3; i++) {
        booleanList.add(true);
    }

    for(int i = 3; i < lisM.size();i+=3) {
        int m = Integer.parseInt(lisM.get(i)); // here I changed the casting to parsing and moved it out of the for loop, there is no need to initialize it again every single time since you do not change it in the second for loop.
        for (int j = 6; j < lisM.size(); j += 6) {
            int m1 = Integer.parseInt(lisM.get(j));// here I changed the casting to parsing again.
            if (m > m1) { // this makes no sense here because you are going over all of the elements of the list and comparing them to all of them. But I kept it here for the sake of example.
                booleanList.set(i/3,false); 
            }

// 如果您想查看整個列表,則必須清除列表並為每個元素重新開始。 下面是如何在不包含不需要的元素的情況下創建新列表的方法:

ArrayList<String> newLisM = new ArrayList<>();

for (int i = 0; i <booleanList.size(); i++) {
        if(booleanList.get(i))
            for (int j = 0; j < 3; j++) {
                newLisM.add(lisM.get(i+j));
            }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM