How to unpack an array into different arguments on method call

后端 未结 3 1178
误落风尘
误落风尘 2021-02-14 02:31

I would like to know if it is possible to unpack an Object array into separate Object on method call which accepts vargs. This question is similar to this one.

I have a

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-14 03:22

    Well, there is no syntactic sugar à la Python or Lua for that in Java, but you can create your own unpack method:

    @SafeVarargs
    public static  Object[] unpack(E... objects) {
        List list = new ArrayList();
        for (Object object : objects) {
            if (object instanceof Object[]) {
                list.addAll(Arrays.asList((Object[]) object));
            }
            else{
                list.add(object);
            }
        }
    
        return list.toArray(new Object[list.size()]);
    }
    
    
    

    This will returns an array containing all the input elements, unpacked.

    Then you can call it in your main method:

    res = doWork(unpack("three", res));
    

    The reason I make this method generic is that you can call it with, for example, a String[] array, without generating a warning. For some reason, the Java compiler thinks that this method has a chance of "polluting the heap", but it is not the case, that's why I added a @SafeVarargs annotation.

    提交回复
    热议问题