Creating an array while passing it as an argument in Java

无人久伴 提交于 2019-12-09 02:12:26

问题


Is there a way to create an array of objects as part of a constructor or method? I'm really not sure how to word this, so I've included an example. I have an enum, and one of the fields is an array of numbers. Here is what I tried:

public enum KeyboardStuff {

    QWERTY(1, {0.5f, 1.3f, 23.1f}, 6);
    DVORAK(5, {0.1f, 0.2f, 4.3f, 1.1f}, 91);
    CHEROKEE(2, {22.0f}, 11);

    private int number, thingy;
    private float[] theArray;

    private KeyboardStuff(int i, float[] anArray, int j) {
        // do things
    }

}

The compiler says that the brackets { } are invalid and should be removed. Is there a way I can pass an array as an argument without creating an array of objects beforehand?


回答1:


You can try with new float[] { ... }.

public enum KeyboardStuff {

    QWERTY(1, new float[] {0.5f, 1.3f, 23.1f}, 6);
    DVORAK(5, new float[] {0.1f, 0.2f, 4.3f, 1.1f}, 91);
    CHEROKEE(2, new float[] {22.0f}, 11);

    private int number, thingy;
    private float[] theArray;

    private KeyboardStuff(int i, float[] anArray, int j) {
        // do things
    }

}



回答2:


Following @Dave's suggest I would use a vararg

QWERTY(1, 6, 0.5, 1.3, 23.1);
DVORAK(5, 91, 0.1, 0.2, 4.3, 1.1);
CHEROKEE(2, 11, 22.0);

private final int number, thingy;
private final double[] theArray;

private KeyboardStuff(int number, int thingy, double... theArray) {
    // do things
}

It is pretty rare that using a float is better than using a double. double has less rounding error and only uses 4 more bytes.




回答3:


Is there a way you can pass an array without creating an array?

No, but you could use varargs to make it mostly-invisible, although that int at the end might need to move.




回答4:


If using Lists's instead of arrays is an option, future versions of Java might start supporting a 'collection literals' syntax which unfortunately doesn't seem to have made it into Java 8:

public enum KeyboardStuff {

    QWERTY(1, [0.5f, 1.3f, 23.1f], 6);
    DVORAK(5, [0.1f, 0.2f, 4.3f, 1.1f], 91);
    CHEROKEE(2, [22.0f], 11);

    private int number, thingy;
    private List<Float> values;

    private KeyboardStuff(int i, List<Float> values, int j) {
        // do things
    }

}


来源:https://stackoverflow.com/questions/7547722/creating-an-array-while-passing-it-as-an-argument-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!