How to unpack an array into different arguments on method call

后端 未结 3 1179
误落风尘
误落风尘 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:21

    This does not implement the Unpack solution, instead it goes about it by making an overload method as I said in my comment. I do not know if this at all what you wanted, but I got it to work and I felt like I would post this for reference.

    public class Test {
        public static Object doWork(Object... objects){
            System.out.println(objects.length);
            return objects;
        }
    
        // this is the method that will concatenate the arrays for you
        public static Object doWork(Object[] objects1, Object... objects2){
            System.out.println(objects1.length + "+" + objects2.length);
            Object[] retval = new Object[objects1.length+objects2.length];
            System.arraycopy(objects1, 0, retval, 0, objects1.length);
            System.arraycopy(objects2, 0, retval, objects1.length, objects2.length);
            return retval;
        }
    
        public static void main(String[] args){
            Object res = doWork("one", "two");
            res = doWork((Object[])res, "three");
            Object[] res2 = (Object[])res; // = {one, two, three}
        }
    }
    
    0 讨论(0)
  • 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 <E> Object[] unpack(E... objects) {
        List<Object> list = new ArrayList<Object>();
        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.

    0 讨论(0)
  • 2021-02-14 03:37

    Try to return as an array of Object instead. Then concatenate "three" at the end of the returned array.

    0 讨论(0)
提交回复
热议问题