本程序包含泛型的求最大值方法、返回重复数组列表方法、二分查找法。
泛型--返回最大值:
//泛型--返回最大值
/*
对象A.compareTo(对象B)返回值:
如果A<B,值小于0;如果A=B,值等于0;如果A>B,值大于0
*/
public static <E extends Comparable<E>> E max(E[][] list) {
E max = list[0][0]; //设二维数组的第一个值为最大值
int i = 0; //用于foreach循环的下标
//使用foreach循环遍历二维数组
for (E[] es : list) { //调用compareTo方法判断大小
if(max.compareTo(es[i]) < 0)
max = es[i++];
}
return max;
}
泛型--返回不重复数组列表:
//泛型--返回不重复数组列表
public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list){
ArrayList<E> temp = new ArrayList<>(); //创建一个新数组列表
for (E e : list) { //遍历list
if(!temp.contains(e)) //调用contains()方法判断temp是否包含list的元素对象
temp.add(e); //temp不包含list的相同对象时添加对象
}
return temp;
}
泛型--二分查找法:
返回的下标从0开始;
返回的-(low + 1)表示查找值应插入的下标,即应插入的下标为low,low 从-(low + 1)得出;
方法一:
//泛型--二分查找法
public static <E extends Comparable<E>> int binarySearch(E[] list, E key) {
int low,high,mid;
low = 0; //数组下限
high = list.length - 1; //数组上限
while(low <= high) {
mid = (low + high) / 2; //表示数组中间的下标
if(key.compareTo(list[mid]) < 0) //如果key小于中间值,上限为| 中间下标-1 |
high = mid - 1;
else if(key.compareTo(list[mid]) > 0) //如果key大于中间值,下限为| 中间下标+1 |
low = mid + 1;
else
return mid; //如果key==中间值,直接返回下标
}
return -(low + 1);
}
方法二:
//泛型--二分查找法
public static <E extends Comparable<E>> int binarySearch(E[] list, E key) {
//直接调用Arrays类的binarySearch(Object[] object, Object e)方法
return Arrays.binarySearch(list, key);
}