简体   繁体   中英

Use a static variable or method for a constant array in Java

I'm wondering if it is better to use a final static variable or method to provide a constant array in Java.

Say we have:

public class myColor {
    public final static String[] COLOR_NAMES = new String[] {"red", "green"};
    public final static String[] colorNames() {return new String[] {"red", "green"};}
}

To me, the second one has the disadvantage that each time it's called a new String array is created. But the first one has the disadvantage, that anyone could do COLOR_NAMES[0] = "blue" .

To clarify: I specifically want to provide a list of color names for a subsequent match with regular expressions.

Is there any established way how this is typically solved?

You can use enum

public enum Color{ 

  RED("red"), GREEN("green");
   final String color;

  Color(String color) {
    this.color=color;
  }

  public String getColor() {
    return color;
  }
 }

This question is fall for using Enum . Personally I wont be using any method for that. But weather static array is good solution for that? It is better to solve it using java enums .

To initialise an array at construction time you can specify a list values in curly braces:

private static final String[] STRING_ARRAY = {"red", "green", "blue"};

In my example I have assumed that you won't want to change the instance of array and so have declared it final. You still would be able to update individual entries like so:

 array[0] = "1";

But you won't be able to replace the array with a different one completely. If the values are going to change a lot - especially if the number of values are going to change - then it may be worth considering using List instead.

If you can go with a list, one option would be:

public final static List<String> COLOR_NAMES = Collections.unmodifiableList(
                                                   Arrays.asList("red", "green"));

You can always get an array if needed:

String[] array = COLOR_NAMES.toArray(new String[0]);

Otherwise your second option is fine although I would write it:

private final String[] COLOR_NAMES = {"red", "green"};
public static String[] getColorNames() { return COLOR_NAMES.clone(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM