如何将Object []转换为int [] java?

时间:2016-07-25 23:42:30

标签: java types casting

这会导致complie错误,我认为这是因为int不是从Object继承的,但有没有遍历每个项目进行转换的解决方案?

Object[] A1 ={1,2,3,4};
int [] B1 = (int[]) A1;

转换为Integer

没有问题
Object[] A1 ={1,2,3,4};
Integer [] B1 = (Integer[]) A1;

我知道我们可以做到

   int [] C = new int[B1.length];
   for(int i=0;i<B1.length;i++)
     C[i] = Integer.valueOf(B[i]);

但是,有没有自动播放方法?

2 个答案:

答案 0 :(得分:2)

即使源数组中的所有对象都是Object[]个对象(如您的示例),也无法int[]强加给Integer Object[] A1 = {1,2,3,4}; ),因为所有的值都需要 unboxed ,而不仅仅是强制转换。

Object[] A1 = new Object[4];
A1[0] = Integer.valueOf(1);
A1[1] = Integer.valueOf(2);
A1[2] = Integer.valueOf(3);
A1[3] = Integer.valueOf(4);

该语句实际上是为您自动装箱4个整数文字,因此编译器将其转换为:

public static void main(java.lang.String[]) throws java.lang.Exception;
  Code:
     0: iconst_4
     1: anewarray     #3                  // class java/lang/Object
     4: dup
     5: iconst_0
     6: iconst_1
     7: invokestatic  #19                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    10: aastore
    11: dup
    12: iconst_1
    13: iconst_2
    14: invokestatic  #19                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    17: aastore
    18: dup
    19: iconst_2
    20: iconst_3
    21: invokestatic  #19                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    24: aastore
    25: dup
    26: iconst_3
    27: iconst_4
    28: invokestatic  #19                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
    31: aastore
    32: astore_1
    33: return

从这个反编译中可以看出:

// Using cast to specific type and auto-unboxing (object cast)
int[] arr1 = new int[A1.length];
for (int i = 0; i < A1.length; i++)
    arr1[i] = (Integer)A1[i];

// Using cast to specific type and explicit unboxing
int[] arr2 = new int[A1.length];
for (int i = 0; i < A1.length; i++)
    arr2[i] = ((Integer)A1[i]).intValue();

// Using cast to more generic type and value extraction
int[] arr3 = new int[A1.length];
for (int i = 0; i < A1.length; i++)
    arr3[i] = ((Number)A1[i]).intValue();

// Using Java 8 streams with method references
int[] arr4 = Arrays.stream(A1)
                   .map(Integer.class::cast)
                   .mapToInt(Integer::intValue)
                   .toArray();

// Using Java 8 streams with lambda expression with auto-unboxing (primitive cast)
int[] arr5 = Arrays.stream(A1)
                   .mapToInt(o -> (int)o)
                   .toArray();

任何解决方案都必须遍历每个项目以取消显示值,无论是显式还是隐式。

各种方法:

{{1}}

答案 1 :(得分:1)

正如您在问题中所承认的那样,int并未扩展Object,因此强制转换是没有意义的,并且编译器正确地抱怨。

可能最安全,最简单的方法是:

Object[] objects = {1, 2, 3, 4};
int[] ints = Arrays.stream(objects).mapToInt(o -> (int)o).toArray();

不是特别优雅,但在Object数组中也不存储整数数组: - )