代码1
package com.atguigu.day16; /* 泛型:类型化参数 实参和形参 泛型的好处: 1.可以节约代码 2.可以让代码的可读性更强 * */ public class Demo2 { public static void main(String[] args) { Pig<String> pig1 = new Pig<>("佩琪","very good"); Pig<Double> pig2 = new Pig<>("乔治",100.0); Pig<Integer> pig3 = new Pig<>("特洛伊",99); System.out.println(pig1);//Pig{name='佩琪', score=very good} System.out.println(pig2);//Pig{name='乔治', score=100.0} System.out.println(pig3);//Pig{name='特洛伊', score=99} } } class Pig<T>{ String name; T score; public Pig() { } public Pig(String name, T score) { this.name = name; this.score = score; } @Override public String toString() { return "Pig{" + "name='" + name + '\'' + ", score=" + score + '}'; } }
代码2
package com.atguigu.day16; /* T extends Number & Comparable<T> T既是Number的孩子,也是Comparable的孩子,指定了T的上限,类型范围不能超过父类 * */ import java.math.BigDecimal; public class Demo3 { public static void main(String[] args) { Integer i; Double d; BigDecimal b; SumTools<Integer> sumTools = new SumTools<>(1,5); Integer sumValue = sumTools.getSum(); System.out.println(sumValue);//6 BigDecimal b1 = new BigDecimal(10.1); BigDecimal b2 = new BigDecimal(20.1); SumTools<BigDecimal> sumTools1= new SumTools<>(b1,b2); BigDecimal b3 = sumTools1.getSum(); System.out.println(b3);//30.2000000000000010658141036401502788066864013671875 } } class SumTools<T extends Number & Comparable<T>>{ private T t1; private T t2; public SumTools(T t1, T t2) { this.t1 = t1; this.t2 = t2; } public T getSum(){ if (t1 instanceof Integer && t2 instanceof Integer){ Integer values = Integer.valueOf((Integer)t1+(Integer)t2); return (T) values; }else if (t1 instanceof BigDecimal){ BigDecimal b1 = (BigDecimal)t1; BigDecimal b2 = (BigDecimal)t2; BigDecimal values = b1.add(b2); return (T) values; } throw new UnsupportedOperationException("类型不对"); } }
代码3
//泛型方法 public class MyArrays { public static <T extends Comparable> void sort(T[] arr){ for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-i-1; j++) { if (arr[j].compareTo(arr[j+1])>0){ T t = arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } } } } } import java.util.Arrays; public class Demo4 { public static void main(String[] args) { MyArrays myArrays = new MyArrays(); Dog dog1 = new Dog("哮天",12); Dog dog2 = new Dog("大黄",10); Dog dog3 = new Dog("小黑",11); Dog[] dogsList = {dog1,dog2,dog3}; myArrays.sort(dogsList); System.out.println(Arrays.toString(dogsList)); //[Dog{name='大黄', age=10}, Dog{name='小黑', age=11}, Dog{name='哮天', age=12}] } } class Dog implements Comparable{ String name; int age; public Dog() { } public Dog(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Object o) { Dog dog = (Dog)o; return this.age-dog.age; } }
代码4