Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The code has a class declaring two different versions of the countContains() met

ID: 3856125 • Letter: T

Question

 The code has a class declaring two different versions of the countContains() method. The methods you will be writing in CountContains each have two parameters: the first has/can access the elements to review and the second parameter, an Object named obj. The method count and return the number of times obj appears as an element in the data accessed using the first parameter. Remember that elements and obj can be null. While not required, a little thought may let you complete one of these methods with only a single line of code. Code: package edu.sbu.cse116;  import java.util.Iterator; import java.util.List;  public class CountContains {   public int countContains(Iterator it, Object obj) {    }    public int countContains(List al, Object obj) {    } } 

Explanation / Answer

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CountContains {

       public int countContains(Iterator it, Object obj) {
           int c=0;
           while(it.hasNext()) {
           Object element = it.next();
           if(element.equals(obj))
               c++;
           }
           return c;

       }

       public int countContains(List al, Object obj) {
           int c=0;
           for (Object e: al)
           {
               if(e.equals(obj))
                   c++;
                 
               }
           return c;

       }

   public static void main(String[] args) {
       // TODO Auto-generated method stub
      
       List<Integer> numbers = new ArrayList<Integer>();
       //add numbers
       numbers.add(1);
       numbers.add(2);
       numbers.add(3);
       numbers.add(2);
       CountContains c=new CountContains();
       Iterator it=numbers.iterator();//assign list to iterator
       System.out.println("Using List 2 count is "+c.countContains(numbers, 2));
       System.out.println("Using Iterator 2 count is "+c.countContains(it, 2));


   }

}

=======================================================================

Output:

Using List 2 count is 2
Using Iterator 2 count is 2