Pass an Array to a Constructor without declaring it?

后端 未结 1 1291
轮回少年
轮回少年 2021-01-13 05:08

In processing, I have defined the following class:

class SomeClass {
    SomeClass(int[] someArray) {
        println(someArray);
    }
}

N

1条回答
  •  轮回少年
    2021-01-13 05:31

    You still need to define it somehow before you send it in... Try this:

    SomeClass myVar = new SomeClass(new int [] {
        12, 10
    });
    

    or you could try some of Java's syntactic sugar...

    class SomeClass {
        SomeClass(int... someArray) {
            println(someArray);
        }
    }
    SomeClass myVar = new SomeClass(12, 10);
    

    which will introduce some restrictions to your coding style... For example you can do this: (special syntax as the last element)

    class SomeClass {
        SomeClass(String someString, float someFloat, int... someArray) {
            println(someString);
            println(someFloat);
            println(someArray);
        }
    }
    SomeClass myVar = new SomeClass("lol",3.14, 12, 10);
    

    but not this: (special syntax not as the last element)

    class SomeClass {
        SomeClass(String someString, int... someArray, float someFloat) {
            println(someString);
            println(someFloat);
            println(someArray);
        }
    }
    SomeClass myVar = new SomeClass("lol", 12, 10,3.14);
    

    Arrays are fun!!

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