import java.util.ArrayList; /* * This work is my own. * @author ajpretor * CSC 330, Spring 2014 * Homework Assignment 1 */ public class ajpretor_hwk1{ /* * @param T t */ public T t; public void set(T t) { this.t = t; } public T get() { return t; } //Array of generic type //ArrayList input= new ArrayList(); //Interface used to specify the second parameter to contains. static public interface Check { boolean ok( T item); //item T is ok (negative e.g.) } public static boolean contains(T[] input, Check c) { /* * loop thru items in array and test using appropriate Check * return true & exit loop if true is reached (if any integer meets the * specified condition); otherwise, return false */ for (int i=0; i { @Override public boolean ok( Integer val) { return val < 0; } } //Class used to test if input is prime. static public class Prime implements Check { @Override public boolean ok( Integer val) { //check if even if (val%2==0) return false; //if odd, check divisibility of #s thru sqrt of val to test if prime for (int i=3; i*i<=val; i+=2){ if(val%i==0) return false; } return true; } } //Class used to test if input is a perfect square. static public class PerfectSquare implements Check { @Override public boolean ok( Integer val) { //take integer sq rt of val int sqrt = (int) Math.sqrt(val); //if square of this equals val, then perfect square if(sqrt*sqrt == val){ return true; } return false; } } public static void main(String[] args){ //Sample array in problem 4.40 text; could not get generic arraylist to work int [] input = {100, 37, 49}; // test conditions /* * I could not get this to work, and so the rest of my code is * "commented out." I am not sure where exactly the problem is, but it * appears to be some data type discrepancy between my generic and * what is required by Prime, PerfectSquare, and Negative. */ //boolean result1 = contains( input, new Prime() ); //boolean result2 = contains( input, new PerfectSquare() ); //boolean result3 = contains( input, new Negative() ); // output results //System.out.println(result1); //System.out.println(result2); //System.out.println(result3); } }