Java two varargs in one method

后端 未结 12 2230
小鲜肉
小鲜肉 2020-11-27 21:08

Is there any way in java, to create a method, which is expecting two different varargs? I know, with the same object kind it isn\'t possible because the compiler does\'nt kn

12条回答
  •  萌比男神i
    2020-11-27 22:08

    This is an old thread, but I thought this would be helpful regardless.

    The solution I found isn't very neat but it works. I created a separate class to handle the heavy lifting. It only has the two variables I needed and their getters. The constructor handles the set methods on its own.

    I needed to pass direction objects and a respective Data object. This also solves the possible problem of uneven data pairs, but that is probably only for my usage needs.

    public class DataDirectionPair{
    
        Data dat;
        Directions dir;
    
        public DataDirectionPair(Data dat, Directions dir) {
            super();
            this.dat = dat;
            this.dir = dir;
        }
    
        /**
         * @return the node
         */
        public Node getNode() {
            return node;
        }
    
        /**
         * @return the direction
         */
        public Directions getDir() {
            return dir;
        }
    }
    

    I would then just pass this class as the vararg for the method

    public void method(DataDirectionPair... ndPair){
        for(DataDirectionPair temp : ndPair){
            this.node = temp.getNode();
            this.direction = temp.getDir();
            //or use it however you want
        }
    }
    

提交回复
热议问题