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

该博客展示了JDK中自动装箱和拆箱的相关代码。代码中包含将primitive类型转换成复合对象(如int转Integer),以及将复合对象转换成primitive类型的操作。还给出了一个使用TreeMap统计字符串数组元素频率的示例,以及一个primitive int数组的List适配器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

};

}

 

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值