作为家庭作业,我需要重构教科书中的代码。目标是使用findMax方法和函数对象技术,找到" findMax"一个Character和String数组,其中findMax将返回字母表中最后一个字符的字符串,对于字符串,它将返回以字母表中最后一个字母开头的字符串,忽略区分大小写。我的问题是,如果我做得对(我显然有些疑惑)?我不想要错误或警告。我也不想复制和粘贴答案。我只想更好地了解如何做到这一点。这是代码:
import java.util.Comparator;
public class Lab1q6 {
public static <AnyType extends Comparable<? super AnyType>>
AnyType findMax( AnyType [ ] arr, Comparator<? super AnyType> cmp ){
int maxIndex = 0;
for(int i=1; i < arr.length; i++)
if( cmp.compare( arr[ i ], arr[ maxIndex ] ) > 0 )
maxIndex = i;
return arr[ maxIndex ];
}
public static class CaseInsensitiveCompare<AnyType extends Comparable<AnyType>> implements Comparator<AnyType>
{
public int compare( String lhs, String rhs )
{ return lhs.compareTo( rhs ); }
@Override
public int compare(AnyType o1, AnyType o2) {
return o1.compareTo( o2 );
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
String [] array = {"owl", "zebra", "GATOR", "Ant", "Reindeer"};
Character [] arr = {'C', 'Z', 'A', 'R', 'S'};
System.out.println( findMax(arr, new CaseInsensitiveCompare()));
System.out.println( findMax(array, new CaseInsensitiveCompare()));
}
}