注意点:基本类型是值类型(比如int)
类类型是引用类型(reference type)
因此Java中通常是引用传递
比如void print(List<Integer> l),
print(l),这种函数传递参数的方式便是使用的引用传递,而C++不使用指针与引用的时候是使用的值传递
来自该网址
http://docs.oracle.com/javase/tutorial/java/generics/methods.html
http://docs.oracle.com/javase/tutorial/extra/generics/index.html
泛型Generics
泛型类的例子
public class Box<T> { // T stands for "Type" private T t; public void set(T t) { this.t = t; } public T get() { return t; } }
泛型类型的调用
Box<Integer> integerBox;
实例化泛型类对象
Box<Integer> integerBox = new Box<Integer>();
The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the
method's return type
泛型方法的类型参数包含在尖括号内,出现在方法的返回类型前
public class Util { // Generic static method public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) { return p1.getKey().equals(p2.getKey()) && p1.getValue().equals(p2.getValue()); } }
泛型方法的调用
boolean same = Util.<Integer, String>compare(p1, p2);
也可以简化成
boolean same = Util.compare(p1, p2);
编译器会推断泛型方法的参数类型
This feature, known as type inference, allows you to invoke a generic method as an ordinary method,
without specifying a type between angle brackets
List<String> ls = new ArrayList<String>(); // 1
List<Object> lo = ls; // 2
lo.add(new Object()); // 3
String s = ls.get(0); // 4: Attempts to assign an Object to a String!
Java对象的赋值相当于引用传递,lo与ls指向内存中的同一个对象,这样就导致问题
import java.util.*; public class Test1 { static void printList(List<?> l){ for(Object o:l){ System.out.println(o); } } public static void main(String[] args){ List<Integer> l=new ArrayList<Integer>(); l.add(new Integer(5)); l.add(new Integer(6)); l.add(new Integer(7)); printList(l); } }
List<? extends Shape> shapes
便只能匹配从类Shape派生出的类型
generic method should not be used.
class Collections { public static <T> void copy(List<T> dest, List<? extends T> src) { ... }
若把该方法改为
class Collections { public static <T, S extends T> void copy(List<T> dest, List<S> src) { ... }
因为S只在参数src中使用,所以用泛型不合适,可以改为通配符。
zero or more statements between balanced braces. You typically find local classes defined in the body of a method.