简体   繁体   English

如何创建一个循环,在 java 中的 ArrayList 中找到每个不同的数字?

[英]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.

相关问题 我如何让应用程序添加数组列表中整数的所有值,以便我可以找到每个年级的中位数? - How would I make the application add all the values of the integers in the arraylist so I could find the median of each grade? 在Java中,每次迭代时如何在循环内清空缓冲区? - How do I empty the buffer inside the loop each iteration in Java? 我可以在 for 循环中运行 while 循环吗? [Java] 如果是这样,在这种情况下我该怎么做? - Can I run a while loop inside a for loop? [Java] If so, how would I do it in this scenario? java-如何为每个子类制作一个ArrayList? - java - how do you make one ArrayList for each subclass? 我如何访问用于每个循环的另一个类中的 ArrayList - How do i access ArrayList that is in another class using for each loop 如何计算ArrayList中每个项目的数量,然后显示它们? - How do I count the number of each item in an ArrayList, then display them? 如何为每个循环填写一个ArrayList? (JAVA) - How to fill out an ArrayList with for each loop? (Java) 我如何在循环中找到第n个项? 爪哇 - how would I find the nth term in a loop? java 在java中,我如何找到第n个斐波那契数? - In java, how would I find the nth Fibonacci number? 如何遍历Java中的2D ArrayList并填充它? - How do I loop thorough a 2D ArrayList in Java and fill it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM