Question 10.. 15 marks You are required to write a list class, MeList, that has a filter method that takes an anonymous
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am
Question 10.. 15 marks You are required to write a list class, MeList, that has a filter method that takes an anonymous
Question 10.. 15 marks You are required to write a list class, MeList, that has a filter method that takes an anonymous inner class as a formal parameter: interface MeList<A> { void filter (Filter<A> f); } The interface Filter declares the form of the anonymous class, whose instances you will pass to the filter method. interface Filter<A> { boolean test (As): } To simplify things you are given a possible implementation of the MyList class. import java.util.ArrayList; import java.util.Iterator; class MyList<A> implements MeList<A> { ArrayList<A> 1 new ArrayList<A>(); MyList (ArrayList<A> 11) { 1 - 11: } public void filter(Filter<A> f) { for (Iterator<A> i 1.iterator(); i.hasNext();) { if (!f.test(i.next())) { // don't forget the negation! i.remove(); } } } } (a) Assume that you are given an ArrayList<Integer> il. What is the actual parameter to filter, which will remove all those ele- ments from il that are divisible by 3 (to check if n is divisible by 3, simply check that n mod 3 = 0). (b) Use this filter technique to implement the Sieve of Eratosthenes. The sieve is a technique to compute all prime numbers between 2 and an upper bound n. To sieve out all non-prime numbers, you should • Create an ArrayList <Integer> of n numbers: 2,3..... n. • Iterate i from 2 to n/2. (n/2 is not the best upper bound, but that doesn't matter.) While you iterate, filter from your arraylist all those numbers k that are greater than i, and divisible by i (which means that k mod i = 0). The interface for Sieve is interface Sieve { void sieve(): } Provide an implementation of Sieve. 5 marks 10 marks