java 在 ArrayList 中查找重复值的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5754592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding index of duplicate values in an ArrayList
提问by Ankit
I have an ArrayList which contains duplicate values at diff diff index.
for example {"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
as u can see the value - "Indian"
exists at index - 0
, 4
& 6
.
我有一个 ArrayList,其中包含 diff diff 索引处的重复值。例如{"Indian","American","Chinese","Australian","Indian","Russian","Indian"}
你可以看到值 -"Indian"
存在于索引 - 0
, 4
& 6
。
I need to know all these indexes where "Indian"
exists and create an arrayList of that.
Here is my code:
我需要知道所有这些索引在哪里"Indian"
存在并创建一个 arrayList 。这是我的代码:
public void filter(){
categoryArray = Arrays.asList(category);
for(String k : category){
//Log.v("filter", filterTerm);
if(k.equals(filterTerm.toLowerCase()))
{
int p = categoryArray.indexOf(k);
Log.v("index of categArr", ""+p);
String id = Integer.toString(p);
indexes.add(id);
}// end of if
}// end of for
Here I get how many times duplicate occurs by getting the size of indexes(ArrayList)
but when I check the values . Its one value at all index since in the method : indexOf()
it always brings the index of first value that it finds in the Array.
在这里,我通过获取索引(ArrayList)的大小来获得重复发生的次数,但是当我检查值时。自从在方法中以来,它在所有索引中都是一个值:indexOf()
它总是带来它在数组中找到的第一个值的索引。
So if duplicate exists at index - 2
,5
,7
I get the array size of index as 3
.
But the values are {2,2,2,};
因此,如果重复项存在于索引 - 2
, 5
,则索引7
的数组大小为3
。但价值观是{2,2,2,};
采纳答案by Robin Green
You need to know which index in the array you are currently at, not the first index where it is to be found. To keep track of that, put
您需要知道您当前在数组中的哪个索引,而不是要找到它的第一个索引。为了跟踪那个,把
int i = 0;
before the loop, and at the very endof the loop put
在循环之前,并在最末端循环的放
i++;
Then the variable i
tells you where you have found the value, so you can add i
to the indexes list.
然后变量会i
告诉您在哪里找到该值,以便您可以将其添加i
到索引列表中。
回答by Don Roby
This is a situation where an index-based for loop is more appropriate than enhanced for loop that you're using, as what you need to grab is the index.
在这种情况下,基于索引的 for 循环比您正在使用的增强型 for 循环更合适,因为您需要获取的是索引。
You can base all your work on the original array rather than converting it to a list, and I suspect you were going for case-insensitive match.
您可以将所有工作基于原始数组,而不是将其转换为列表,而且我怀疑您要进行不区分大小写的匹配。
public void filter(){
for(int i=0; i<category.length; i++){
if(category[i].equalsIgnoreCase(filterTerm))
{
String id = Integer.toString(i);
indexes.add(id);
}
}
}
If you have an ArrayList rather than an array, of course similar code will work, but using list.get(i)
instead of category[i]
.
如果您有一个 ArrayList 而不是数组,当然类似的代码将起作用,但使用list.get(i)
代替category[i]
.