Using generics, in some cases, can effectively reduce the amount of code.
The pair generic class can be constructed according to the type of parameter passed in.
Minmax are generic methods, arrays of different data types, and can get their min max value, it should be noted that the t[] class type must be implemented comparable method, otherwise the CompareTo () method cannot be called.
In addition, the type of the generic must be a class type, int, double, Float this is not possible, must be an integer, double, float, String, studentclass this kind of type.
/** Generic class * Created by Sophie on 15/7/10. * * Public class Pair<T> { PrivateT Max;PrivateT min; Public Pair(t max, T min) { This. max = max; This. min = min; }/** * Generic method * @return */ PublicTGetmax(){return This. Max; }/** * Generic method * @return */ PublicTGetmin(){return This. Min; }}
Public class Calc { /** * Generic method, and this type T is implemented with the comparable interface, otherwise it cannot be used. CompareTo () method * @param nums * @param <T> * @return * * Public Static<t extends Comparable>pair<t>Minmax(t[] nums) {T max; T min;if(Nums.length = =1) {max = nums[0]; Min = nums[0]; }Else{max = nums[0]; Min = nums[0]; for(inti =0; i < nums.length; i++) {if(Nums[i].compareto (max) >0) max = Nums[i];if(Nums[i].compareto (min) <0) min = nums[i]; } }return NewPair<t> (max,min); }}
ImportJava.text.SimpleDateFormat;ImportJava.util.GregorianCalendar;/** * Created by Sophie on 15/7/10. * * Public class Test { Public Static void Main(string[] args) {/ * integer[] a = new integer[]{1,2,3,4,5,6,7,8,9}; System.out.println ("Max =" +calc.minmax (a). Getmax () + "; Min = "+calc.minmax (a). Getmin ()); */ / * string[] a = new string[]{"abc", "AaB", "AAA", "01a"}; System.out.println ("Max =" +calc.minmax (a). Getmax () + "; Min = "+calc.minmax (a). Getmin ()); */Gregoriancalendar[] A =Newgregoriancalendar[]{NewGregorianCalendar (1989,Ten, A,9, -,xx),NewGregorianCalendar (1989,9, -, One, at, -),NewGregorianCalendar (1989,Ten, A,9, -, -) }; SimpleDateFormat DF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); System.out.println ("Max ="+df.format (Calc.minmax (a). Getmax (). GetTime ()) +"\nmin ="+df.format (Calc.minmax (a). Getmin (). GetTime ()); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java generic-Class generic methods