package cn.tedu.struect.generic;
import java.util.Comparator;
public class Demo02_genericLimit {
public static void main(String[] args) {
String[] arr = {
"cZaZEBRA",
"alligator",
"crocodile"
};
System.out.println(
GenericMemoryCell.findMax(
arr,
new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}
)
);
}
}
class CaseInsensitiveCompare implements Comparator<String>{
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
}
package cn.tedu.struect.generic;
import java.util.Comparator;
public class GenericMemoryCell <AnyType> {
private AnyType storedValue;
public AnyType read() {
return storedValue;
};
public void write(AnyType x) {
storedValue = x ;
}
public static <AnyType> boolean contains(AnyType[] arr , AnyType x ) {
for(AnyType val : arr) {
if(x.equals(val)) {
return true ;
}
}
return false ;
}
public static <AnyType extends Comparable<? super AnyType>> AnyType findMax(AnyType[] arr) {
int maxIndex =0 ;
for(int i=1 ; i<arr.length ; i++) {
if(arr[i].compareTo(arr[maxIndex])>0) {
maxIndex = i ;
}
}
return arr[maxIndex] ;
}
public static <AT> AT findMax(AT[] arr , Comparator<? super AT> cmp ) {
int maxIndex = 0 ;
for(int i=1 ; i<arr.length ; i++) {
if(cmp.compare(arr[maxIndex], arr[i]) < 0) {
maxIndex = i ;
}
}
return arr[maxIndex] ;
}
}