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
如果想避免这种因为自动装箱机制导致的性能损失,最好使用专门适用基本类型的容器版本
下面的代码创建了持有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,但是自动包装机制不能用于数组
}
}
还没有评论,来说两句吧...