如何获取不是第一个[重复]的indexOf元素

问题描述 投票:-1回答:4

这个问题在这里已有答案:

Assumed

ArrayList<Integer> list =  Arrays.asList(new Integer[] {1,2,3,4,5,6,1,8,9});

Find second occurence

我想获得(多个)包含元素“1”的第二个发现的索引,但list.indexOf(1)将始终返回0(因为它是第一个发现)。

Performance

我想这样做而不使用像forwhile这样的循环。因为我需要它用于游戏,所以使用循环根本不会有效。

编辑:有没有办法让“indexOf”一些元素没有迭代器?

java arraylist indexof
4个回答
5
投票

没有迭代就不能这样做。 例如,indexOf迭代。

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

同样适用于lastIndexOf。 你可以看到根本没有使用Iterator<Integer>,如果你担心的话。

而且,顺便说一句,这不是一个性能问题。 你有数百万个元素的数组吗?如果有,请考虑更改数据结构类型。


1
投票

如果您非常关注性能,请使用HashMap<Integer, List<Integer>>。然后,如果你想要发生一个元素m,你可以做map.get(m).get(n)。您的地图包含元素及其相应的索引。

构建地图后,查询的时间复杂度将为O(1)

例:

    public static void main(String[] args){
        int[] a = {1, 2, 1, 3, 4, 1};
        Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();

        for(int i = 0; i < a.length; i++){
            if(map.containsKey(a[i])){
                map.get(a[i]).add(i);
            }else{
                map.put(a[i], new ArrayList<Integer>());
                map.get(a[i]).add(i);
            }
        }

        // second index of 1. Note that index starts from 0.

        System.out.println(map.get(1).get(1));
    }

结果:

2


0
投票
list.subList(list.indexOf(1) + 1, list.size()).indexOf(1)

0
投票
list.indexOf(1, list.indexOf(1) + 1);

第一个参数1是要搜索的对象。第二个参数list.indexOf(1) + 1是搜索的起始索引。

© www.soinside.com 2019 - 2024. All rights reserved.