import java.util.*;class TestCollectionsSortByLambda{ public static void main(String[] args) { List<Person> school = new ArrayList<>(); school.add( new Person("Li",23)); school.add( new Person("Wang",28)); school.add( new Person("Zhang",21)); school.add( new Person("Tang",19)); school.add( new Person("Chen",22)); school.add( new Person("Zhao",22)); System.out.PRintln( school ); Collections.sort( school, (p1,p2)->p1.age-p2.age ); System.out.println( school ); int index = Collections.binarySearch( school, new Person("Li",23), (p1,p2)->p1.age-p2.age ); if( index >=0 ) System.out.println( "Found:" + school.get( index )); else System.out.println( "Not Found!" ); }}class Person{ String name; int age; public Person( String name, int age){ this.name=name; this.age=age; } public String toString(){ return name+":"+age; }}
泛型
自定义泛型
import java.util.*;class GenericMethod { public static void main(String[] args){ Date date = BeanUtil.<Date>getInstance("java.util.Date"); System.out.println(date); }}class BeanUtil{ public static <T> T getInstance( String clzName ){ try { Class c = Class.forName(clzName); return (T) c.newInstance(); } catch (ClassNotFoundException ex){} catch (InstantiationException ex){} catch (IllegalaccessException ex){} return null; }}
对泛型的限定
常用算法
遍试算法(枚举)
迭代算法
//求平方根public class Sqrt{ public static void main(String args[]){ System.out.println( sqrt( 98.0 ) ); System.out.println( Math.sqrt(98.0) ); } static double sqrt( double a ){ double x=1.0; do{ x = ( x + a/x ) /2; System.out.println( x + "," + a/x ); }while( Math.abs(x*x-a)/a > 1e-6 ); return x; }}