P9.17 Declare an interface Filter as follows: public interface Filter { boolean
ID: 3710433 • Letter: P
Question
P9.17
Declare an interface Filter as follows:
public interface Filter
{
boolean accept(Object x);
}
Write a method: public static ArrayList collectAll(ArrayList objects, Filter f) that returns all objects in the objects list that are accepted by the given filter.
Provide a class ShortWordFilter whose filter method accepts all strings of length < 5.
Then write a program that asks the user for input and output textfile names, reads all words from inputfile, puts them into an ArrayList, calls collectAll, and prints a list of the short words to the output file.
Explanation / Answer
Below is your code. Please let me know in comments if you have any issue
public interface Filter {
boolean accept(Object x);
}
public class ShortWordFilter implements Filter {
@Override
public boolean accept(Object x) {
String input = (String) x;
if(input.length()<5){
return true;
}
else
return false;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class FilterMain {
public static final String END_STRING = "SENITEL";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Object> list = new ArrayList<Object>();
String input = null;
System.out.println("Enter the words you want to filter press enter after entering each word: ");
System.out.println("Enter '"+END_STRING+"' when you want to stop...");
do{
input = in.next();
if(input.equalsIgnoreCase(END_STRING)){
break;
}
list.add(input);
}
while(!input.equalsIgnoreCase(END_STRING));
in.close();
Filter shortWordFilter = new ShortWordFilter();
ArrayList<Object> filteredList = collectAll(list, shortWordFilter);
System.out.println(" Filtered List");
for(Object x: filteredList){
System.out.print(x+",");
}
}
public static ArrayList<Object> collectAll(ArrayList<Object> objects, Filter f){
ArrayList<Object> returnList = new ArrayList<Object>();
for(Object x: objects){
if(f.accept(x))
returnList.add(x);
}
return returnList;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.