英文:
Is there a better way to create a method that finds whether or not an integer value exists in an ArrayList?
问题
程序有一个包含50个成绩的ArrayList,其中一个被调用的方法应该是用来查找ArrayList中是否存在某个值。这是我所拥有的代码:
public void find(int g) {
int grade = 0;
if (grades.contains(g)) {
grade++;
}
我这样做对吗?
英文:
The program has an ArrayList of 50 grades, and one of the methods that is called is supposed find if a value exists in the ArrayList. This is what I have:
public void find(int g) {
int grade = 0;
if (grades.contains(g)) {
grade++;
}
Did I do this right?
答案1
得分: 2
根据 @markspace 的评论:
> 它基本上和单独的 contains()
做的事情是一样的。
如果你声明一个无返回值的函数,你可能无法看到结果。
所以,局部变量 grade
实际上什么也没做。
只需要这样做:
public boolean isExist(int g) {
return grades.contains(g);
}
如果你想要计算列表中元素的出现次数:
参考:如何计算列表中元素的出现次数?
int occurrences = Collections.frequency(grades, g);
英文:
As @markspace commented:
> It basically does the same thing as contains()
alone.
If you declare a void funciton, you might not be able to see the result.
So, the local variable grade
actually does nothing.
Just do it:
public boolean isExist(int g) {
return grades.contains(g);
}
If you want to calculate the number of occurrences of an element in your list:
Reference: How to count the number of occurrences of an element in a List?
int occurrences = Collections.frequency(grades, g);
答案2
得分: 0
从您发布的代码片段中,如果您的目的是查找大于等于特定数字的成绩数量,您可以像下面的片段中使用 filter
方法:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10);
long count = list.stream().filter(i -> i >= 10).count();
System.out.println("count:" + count);
英文:
From the code snippet you have posted, if your intent is to find out the count of grades that are >= a specified number, you could use the filter
method like in the snippet below
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,10,10,10);
long count = list.stream().filter(i -> i == 10).count();
System.out.println("count:" + count);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论