Can a single Java variable accept an array of either primitives or objects?

前端 未结 6 615
走了就别回头了
走了就别回头了 2021-01-03 12:30

For example, for a single method that reads the elements of an array, how can the programmer allow either an array of objects or an array of primitives to be passed as the p

6条回答
  •  [愿得一人]
    2021-01-03 13:30

    class Test
    {
    public static void main(String[] args)
    {
        run(new String[] {"Hello", "World"});
    
        Integer[] inputs = {1, 2, 3};
    
        run(inputs);
    
                //run(new int[] {1, 2, 3}); //this would not do!
    }
    
    private static void run(Object[] inputs)
    {
        for(Object input : inputs)
            System.out.println(input);
    }
    

    }

    It outputs : Hello World 1 2 3

    So, even with auto-boxing, the array of Objects cannot take primitves because array itself is derived from Object. Hence my answer to the question is NO.

    However, in C# you can have the magic "var" to go around this issue :)

提交回复
热议问题