簡體   English   中英

如何使用另一個數組列表提供的索引比較數組列表中的元素

[英]How to compare elements in an array list using the index provided by another arraylist

我有一個ArrayList: A包含索引array ,類似於[[0,1],[4,5,6]] 這份名單是動態的,基於我有2周整數一些前期操作,我做的規模可能會增長arraylists大小相等的說7 像這樣: B: [1,1,4,5,2,3,2]C: [3,3,4,5,6,6,6]

我需要幫助來比較由arrayList: A in BC表示的索引處的元素

例子:

比較 arrayList B 中索引[0,1]處的元素並檢查list.get[0] == list.get[1][4,5,6]檢查是否list.get[4] == list.get[5] == list.get[6]

array list C相同

非常感謝任何幫助。 提前致謝

正如您所說,使用 arraylist A的值作為其他列表的索引:

示例A = [0,1] , B[3, 3]

您需要檢查是否:

B[0] == B[1]

但是將索引重寫為A值,您會得到:

B[A[0]] == B[A[1]]

只需將其擴展到一般情況即可解決問題。

static boolean checkIndex ( List<List<Integer>> indexList, List<Integer> listToCheck ){
    for (List<Integer> indices : indexList) {
        int val = listToCheck.get( indices.get(0) );
        for (int i = 1; i < indices.size(); i++) {
            int index = indices.get(i);
            if ( listToCheck.get(index) != val ) {
                return false;
            }
        }
    }
    return true;
}

我會循環所有索引列表並檢查另一個列表中相應索引的所有值。

測試

public static void main(String[] args) {
    List<List<Integer>> indexList = new ArrayList<>();
    indexList.add(Arrays.asList(0,1));
    indexList.add(Arrays.asList(4,5,6));
    System.out.println(indexList);
    List<Integer> tempList = Arrays.asList(1,1,4,5,2,3,2);
    List<Integer> tempList2 = Arrays.asList(3,3,4,5,6,6,6);
    System.out.println(tempList);
    System.out.println(checkIndex( indexList, tempList));
    System.out.println(tempList2);
    System.out.println(checkIndex( indexList, tempList2));
}

//輸出

[[0, 1], [4, 5, 6]]
[1, 1, 4, 5, 2, 3, 2]
false
[3, 3, 4, 5, 6, 6, 6]
true

暫無
暫無

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

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