Java的自动包装机制

刚刚开学,今天课少,趁着闲再更新一篇关于Java中泛型博文,废话不多说直接上干货。
任何基本类型都不能作为类型参数。这应该是一个基本的概念,先看看下面的代码:

import java.util.*;

public class ListofInt
{
    public static void main(String[] args)
    {
        List<Integer> li = new ArrayList<Integer>();
        for(int i=0; i<5; i++)
        {
            //这里在向一个参数类型为Integer的List加入一个类型为int的值
            li.add(i);
        }
        for(int i : li)
        //自动包装机制允许foreach产生int
        {
            System.out.print(i + " ");
            //输出:0 1 2 3 4
        }
    }
}

我们并不能创建一个ArrayList<int>,我们只能创建其对应的类ArrayList<Integer>,然后基于Java SE5的自动包装机制可以自动的实现int到Integer的双向转换。
如果想避免这种因为自动装箱机制导致的性能损失,最好使用专门适用基本类型的容器版本

下面的代码创建了持有Byte的Set

import java.util.*;
public class ByteSet
{
    Byte[] possibles = {1,2,3,4,5,6,7,8,9};
    Set<Byte> mySet = new HashSet<Byte>(Arrays.asList(possibles));
    //Set<Byte> mySet2 = new HashSet<Byte>(Arrays.<Byte>asList(1,2,3,4,5,6,7,8,9));
    //这样是不行的,asList方法的参数一定要是一个数组
}

但是你不能寄希望于自动包装机制解决所有的问题,下面的代码将展示这个问题:

import net.mindview.util.*;

class FArray
{
    public static <T> T[] fill(T[] a,Generator<T> gen)
    {
        for(int i=0; i<a.length; i++)
        {
            a[i] = gen.next();
        }
        return a;
    }
}
public class PrimitiveGenericTest
{
    public static void main(String[] args)
    {
        String[] strings = FArray.fill(new String[7], new RandomGenerator.String(10));
        for(String s : strings)
        {
            System.out.println(s);
        }
        Integer[] integers = FArray.fill(new Integer[7],new RandomGenerator.Integer());
        for(int i : integers)
        {
            System.out.println(i);
        }
        //int[] b = FArray.fill(new int[7], new RandomGenerator.Integer());
        //很不幸这个程序并不能正常运行,因为java虽然可以将Integer转化为int,但是自动包装机制不能用于数组
    }
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值