泛型
java原创泛型小于 1 分钟约 225 字
基础应用
package com.example.demo;
import org.junit.Test;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* @author liuhuan
* @title: SortedArray
* @description: TODO
* @projectName dataStructure
* @date 2023/8/2819:49
* @return V1.0.0
*/
public class SortedArray {
public static <T extends Comparable<? super T>> int binarySearch(T[] arr,T arr1){
return arr[0].compareTo(arr1);
}
public static <T extends Comparable<? super T>> List<T> demo1(List<T> arr){
Collections.sort(arr);
return arr;
}
public static <T> T[] swap(T[] t,int i,int j) {
System.out.println("未变**:"+t[i]+"位置:"+i+"__"+t[j]+"位置:"+j);
T tmp=t[i];
t[i]=t[j];
t[j]=tmp;
System.out.println("改变**:"+t[i]+"位置:"+i+"__"+t[j]+"位置:"+j);
return t;
}
public static void main(String[] args) {
int[] arr = new int[1];
arr[0]=1;
System.out.println(SortedArray.binarySearch(new Integer[]{100,200},200));
}
}
警告
<T extends Comparable<? super T>>
这种声明的方式,不仅可以接受T类型,还可以接受T的父类型,这样类型参数对所传入的参数限制更少,提高了 API 的灵活性。