0

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?

  • *a method that finds whether or not an integer value exists* - What is the point of using the "grade" variable? The variable is defined locally and not returned to a calling method, so it effectively does nothing. So I'm not really understanding the point of the method. I would have thought your method would simply return the boolean result of using the contains() method. Since it is a single statement I'm not sure why you would make it a method. I think you need to clarify your requirement. – camickr Sep 24 '20 at 02:24
  • 1
    If you want a count of the number of a kind of grade in an array list, then no. This only finds the first occurrence, not the total. It basically does the same thing as `contains()` alone. – markspace Sep 24 '20 at 02:25

2 Answers2

2

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);
s3cret
  • 354
  • 2
  • 10
0

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);
Prabhu R
  • 13,836
  • 21
  • 78
  • 112