编程语言

img maoxiang

JDK 1.5 特性使用实例3--AutoBoxing

发表于2004/10/10 11:43:00  1064人阅读

分类: Web 开发技术

package maoxiang.examples.jdk15;

 

import java.util.AbstractList;

import java.util.List;

import java.util.Map;

import java.util.TreeMap;

 

/**

* @author 毛翔

*

* box 将primitive 类型转换成复合对象 ,如将int 转换成Integer

* unbox 将复合对象转换成primitive Integer.intValue()

*/

public class AutoBoxing {

 

public static void main(String[] args) {

AutoBoxing test = new AutoBoxing();

test.Test1();

}

 

public void Test1() {

String[] args = new String[] { "1", "2", "3", "4", "5", "6", "7", "8" };

Map<String, Integer> m = new TreeMap<String, Integer>();

for (String word : args) {

Integer freq = m.get(word);

m.put(word, (freq == null ? 1 : freq + 1));

}

System.out.println(m);

 

}

 

//  List adapter for primitive int array

public static List<Integer> asList(final int[] a) {

return new AbstractList<Integer>() {

public Integer get(int i) {

return a[i];

}

 

// Throws NullPointerException if val == null

public Integer set(int i, Integer val) {

Integer oldVal = a[i];

a[i] = val;

return oldVal;

}

 

public int size() {

return a.length;

}

};

}

 

}

阅读全文
0 0

相关文章推荐

img
取 消
img