泛型
一种java的语言特征
使用泛型更安全,适用更广泛
*自定义泛型
public static void main(String[] args){
TNode<String> t = new TNode<>("Roo");
t.add("Left"); t.add("Middle"); t.add("Right");
t.getChild(0).add("aaa");
t.getChild(0).add("bbb");
t.traverse();
}
}
{
private T value;
private ArrayList<TNode<T>> children = new ArrayList<>();
public T getValue() { return this.value; }
public void add(T v) {
TNode<T> child = new TNode<>(v);
this.children.add(child);
}
public TNode<T> getChild(int i) {
if ((i < 0) || (i > this.children.size())) return null;
return (TNode<T>)this.children.get(i);
}
System.out.println(this.value);
for (TNode child : this.children)
child.traverse();
}
}
*自定义泛型方法
public static void main(String[] args){
Date date = BeanUtil.<Date>getInstance("java.util.Date");
System.out.println(date);
}
}
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 static void main(String args[]){
for( int a=1; a<=9; a++ )
for( int b=0; b<=9; b++ )
for( int c=0; c<=9; c++ )
if( a*a*a+b*b*b+c*c*c == 100*a+10*b+c)
System.out.println( 100*a+10*b+c );
}
}
{
public static void main(String args[]){
System.out.println( sqrt( 98.0 ) );
System.out.println( Math.sqrt(98.0) );
}
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;
}
}
{
public static void main(String args[])
{
System.out.println("Fac of 5 is " + fac( 5) );
}
static long fac( int n ){
if( n==0 ) return 1;
else return fac(n-1) * n;
}
}