试图在java中的Arraylist中查找所有出现的对象 [英] Trying to find all occurrences of an object in Arraylist, in java

查看:20
本文介绍了试图在java中的Arraylist中查找所有出现的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 中有一个 ArrayList,我需要在其中找到特定对象的所有出现.方法 ArrayList.indexOf(Object) 只找到一个出现,所以我似乎需要别的东西.

I have an ArrayList in Java, and I need to find all occurrences of a specific object in it. The method ArrayList.indexOf(Object) just finds one occurrence, so it seems that I need something else.

推荐答案

我不认为你需要太花哨.以下应该可以正常工作:

I don't think you need to be too fancy about it. The following should work fine:

static <T> List<Integer> indexOfAll(T obj, List<T> list) {
    final List<Integer> indexList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        if (obj.equals(list.get(i))) {
            indexList.add(i);
        }
    }
    return indexList;
}

这篇关于试图在java中的Arraylist中查找所有出现的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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