如何在arrayList中找到第n个索引 [英] How to find the nth Index in a arrayList

查看:83
本文介绍了如何在arrayList中找到第n个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在数组列表中找到第n个索引例如:我拥有一个 List< Character>charList = new ArrayList< Character>(Arrays.asList('s','h','a','r','a','n'))

how to find the nth index in a arraylist ex: i hv a List<Character> charList = new ArrayList<Character>(Arrays.asList('s', 'h','a','r','a','n'))

charList.indexOf('a'); 

总是给出 a first 索引.如何获得第n个?

always gives the first index of the a. How do I get the nth?

推荐答案

ArrayList中indexOf()的实现:

The implement of indexOf() in ArrayList:

    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;
    }

因此您可以尝试列出以下内容:

So you can try list this:

    public int indexNth(List charList, int n, Object _enum) {
        int index = 0;
        int findTimes = 0;
        if (n == 0)
            return -1;
        if (CollectionUtils.isEmpty(charList))
            return -1;
        for (Object o : charList) {
            if (o.equals(_enum))
                findTimes++;
            if (findTimes >= n)
                return index;
            index++;
        }
        return -1;
    }

这篇关于如何在arrayList中找到第n个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆