【问题标题】:How to compare elements in an array list using the index provided by another arraylist如何使用另一个数组列表提供的索引比较数组列表中的元素
【发布时间】:2019-09-20 03:59:27
【问题描述】:

我有一个ArrayList: A,其中包含array 的索引,类似于[[0,1],[4,5,6]]。这个列表是动态的,可能会根据我之前做的一些操作而增加 我还有两个相同大小的整数arraylists7。像这样的东西: B: [1,1,4,5,2,3,2]C: [3,3,4,5,6,6,6]

我需要帮助来分别比较BBCarrayList: A 表示的索引处的元素

例子:

比较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 也一样

非常感谢任何帮助。提前致谢

【问题讨论】:

  • 请分享你到目前为止的尝试

标签: java arrays arraylist


【解决方案1】:

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

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

您需要检查是否:

B[0] == B[1]

但是将索引重写为A 的值,你会得到:

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

只需将此扩展到一般情况,您就解决了问题。

【讨论】:

  • 确保也进行适当的边界检查
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2013-07-30
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多