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

查看:106
本文介绍了试图在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 ArrayList<Integer> indexOfAll(Object obj, ArrayList list){
    ArrayList<Integer> indexList = new ArrayList<Integer>();
    for (int i = 0; i < list.size(); i++)
        if(obj.equals(list.get(i)))
            indexList.add(i);
    return indexList;
}

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

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