[英]How do I make a loop that would find each distinct number inside an ArrayList in java?
I have a java class called StudentList and I want to make a method which would go through each student and check their group numbers.我有一个名为 StudentList 的 java class ,我想制定一个方法,通过每个学生 go 并检查他们的组号。 Then add them to an arraylist, if the group number is already inside the arraylist then it would skip it.
然后将它们添加到 arraylist 中,如果组号已经在 arraylist 中,那么它将跳过它。 But how do I make a loop that would skip duplicates?
但是如何制作一个跳过重复项的循环呢?
I've tried using the for loop but I can't think of a solution past this one point:我试过使用 for 循环,但我想不出一个解决方案:
public ArrayList<Integer> getAllGroupNumbers() {
ArrayList<Integer> a = new ArrayList<Integer>();
for(int i = 0; i < list.size(); i++)
{
if(list.get(i).getGroupNumber() != ...)
}
}
You can use.contains method in ArrayList to check if an element is already present in the list.您可以使用 ArrayList 中的 .contains 方法来检查列表中是否已经存在元素。 Sample code would be like the one follows.
示例代码如下所示。
for(int i = 0; i < list.size(); i++)
{
Integer groupNumber = list.get(i).getGroupNumber();
if( !a.contains(groupNumber) ) {
a.add(groupNumber);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.