Java的自动包装机制

r囧r小猫 2022-05-30 07:13 169阅读 0赞

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

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

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

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

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

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

  1. import net.mindview.util.*;
  2. class FArray
  3. {
  4. public static <T> T[] fill(T[] a,Generator<T> gen)
  5. {
  6. for(int i=0; i<a.length; i++)
  7. {
  8. a[i] = gen.next();
  9. }
  10. return a;
  11. }
  12. }
  13. public class PrimitiveGenericTest {
  14. public static void main(String[] args)
  15. {
  16. String[] strings = FArray.fill(new String[7], new RandomGenerator.String(10));
  17. for(String s : strings)
  18. {
  19. System.out.println(s);
  20. }
  21. Integer[] integers = FArray.fill(new Integer[7],new RandomGenerator.Integer());
  22. for(int i : integers)
  23. {
  24. System.out.println(i);
  25. }
  26. //int[] b = FArray.fill(new int[7], new RandomGenerator.Integer());
  27. //很不幸这个程序并不能正常运行,因为java虽然可以将Integer转化为int,但是自动包装机制不能用于数组
  28. }
  29. }

发表评论

表情:
评论列表 (有 0 条评论,169人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java自动包装机制

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