黑马程序员——Java 5新特性
---------------------- android培训、java培训、期待与您交流! ----------------------
一、静态导入
import static java.lang.Math.*;
public class StaticImport {
public static void main(String[] args) {
System.out.println(max(5, 1));
System.out.println(max(5, 9));
}
}
二、可变参数
特点:可变参数只能出现在参数列表的最后,调用可变参数的方法时,编译器为该可变参数隐含创建一个数组,在方法体中以数组的形式访问可变参数。
public class VariableParameter {
public static void main(String[] args) {
System.out.println(add(new int[] { 1, 2, 3 }));
}
public static int add(int... nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
}
三、增强的for循环
增强的for循环的加入简化了集合的遍历
其语法如下
– for(type element :array) {
System.out.println(element)....
}
四、枚举(Enums)
JDK1.5加入了一个全新类型的“类”-枚举类型。为此JDK1.5引入了一个新关键字enum. 我们可以这样来定义一个枚举类型:
public enum Color
{ Red, White, Blue }
然后可以这样来使用Color myColor = Color.Red.
枚举类型可用于设计单例模式的类。
l 实例:定义有参构造函数、含抽象方法的枚举类型
public enum TrafficLamp {
RED(30) {
@Override
public TrafficLamp nextLamp() {
return GREEN;
}
},
GREEN(45) {
@Override
public TrafficLamp nextLamp() {
return YELLOW;
}
},
YELLOW(5) {
@Override
public TrafficLamp nextLamp() {
return RED;
}
};
public abstract TrafficLamp nextLamp();
private int time;
private TrafficLamp(int time) {
this.time = time;
}
}
五、泛型(Generic)
泛型是JDK1.5中一个最重要的特征。通过引入泛型,我们将获得编译时类型的安全和运行时更小地抛出ClassCastExceptions的可能。在JDK1.5中,你可以声明一个集合将接收/返回的对象的类型。
实例:在集合类中使用泛型
import java.util.*;
import java.util.Map.Entry;
public class GenericTest {
public static void main(String[] args) throws Exception {
HashMap<String, Integer> map = new HashMap<String,Integer>();
map.put("fengyan", 22);
map.put("hello", 23);
Set<Entry<String, Integer>> keySet =map.entrySet();
for (Entry<String, Integer> key : keySet) {
System.out.println(key.getKey()+": "+key.getValue());
}
}
}
实例:自定义泛型类
import java.util.Set;
public class BaseDao<E> {
public void save(E obj) { }
public E findById(Integer id) { return null; }
public void delete(E obj) { }
public void delete(Integer id) { }
public void update(E obj) { }
public Set<E> findByconditions(String where){ return null;}
}
实例:通过反射获得泛型的实际类型参数
import java.lang.reflect.*;
import java.util.*;
public class GenericTest {
public static void main(String[] args) throws Exception {
Method method = GenericTest.class.getMethod("applyList", List.class);
Type[] types = method.getGenericParameterTypes();
ParameterizedType pType = (ParameterizedType) types[0];
types = pType.getActualTypeArguments();
System.out.println(types[0]);
}
public static void applyList(List<Date> list) {
}
}
详细请查看:http://edu.csdn.net/heima