111111
精灵王
精灵王
  • 注册日期2010-12-08
  • 发帖数640
  • QQ
  • 火币1103枚
  • 粉丝120
  • 关注75
  • 社区明星
阅读:2842回复:0

Java1.5语言新特性简单总结-JSP教程,Java技巧及代码

楼主#
更多 发布于:2011-01-08 20:22
1. 自动装箱和拆箱 对应c#
 例1.1
  integer i = 10;
  int j = i;
  
2. 更优化的for循环 对应就c#---foreach循环
 例2.1
  string[] names = {"badboy","goodboy","happygirl","sadgirl"};
  for(string option: names) {
   system.out.println(option);
  }
 例2.2 加泛型 对应c++模板
  import java.util.*;
  
  arraylist<string> animals = new arraylist<string>();
  animals.add("dog");
  animals.add("cat");
  animals.add("chick");
  animals.add("cow");
  for(string option : animals) {
   system.out.println(option);
  }
  
3.参数可变的方法和printf
 例3.1
  定义:
  public int sum(int... n) {  //传过来n为一个int型数组
   int tempsum;
   for(int option : n) {
    tempsum+=option;
   }
   /*
   for(int i = 0; i < n.length; i++) {
    tempsum+=n;
   }
   */
   return tempsum;
  }
  调用1: sum(1);
  调用2: sum(1,2);
  调用3: sum(1,2,3,4);
 例3.2 printf方法,  对应c语言的printf
  int x = 10;
  int y = 20;
  int sum = x + y;
  system.out.printf("%d + %d = %d",x,y,sum);
4. 枚举
 例4.1
  public enum mycolors {
   red,
   black,
   blue,
   green,
   yellow
  }
  
  mycolors color = mycolors.red;
  for(mycolors option : color.values()) {
   system.out.println(option);
  }
/**不能在switch语句里这样写case mycolors.red:
 *这样编译器不会让你通过*/
switch(color) {
 case red:
  system.out.println("best color is "+red);
  break;
 case black:
  system.out.println("no " + black);
  break;
 default:
  system.out.println("what");
  break;
}
5.静态引用
 例5.1
  1.5版本以前的写法是:
 
    import java.lang.math; //程式开头处
  
    ...
  
    double x = math.random();
  1.5版本中能这样写
   import static java.lang.math.random; //程式开头处
  
   ...
    
   double x = random();  


喜欢0 评分0
游客

返回顶部