14

I am choosing randomly from set of particular strings in my application. I store those data in the code directly. As far as I know, you can't declare public static final String[] = {"aa", "bb"}. So I though the enum would be useful, which works fine with one-word names:

public enum NAMES {
  Mike, Peter, Tom, Andy
}

But how do I store sentences like this? Here the enum fails:

public enum SECRETS {
  "George Tupou V, the King of Tonga, dies in Hong Kong at the age of 63.",
  "Joachim Gauck is elected President of Germany.",
  "Lindsey Vonn and Marcel Hirscher win the Alpine Skiing World Cup.";
}

What else should I use? Or am I using the enum incorrectly?

2
  • 2
    SECRETS(String string) Then you can do: GEORGE("George....") Enums are the same as classes but the () is optional when there are no parameters. Commented Mar 19, 2012 at 21:09
  • 2
    Re: "As far as I know, you can't declare public static final String[] = {"aa", "bb"}": What makes you say that? Aside from the lack of a field-name between String[] and =, it looks perfectly correct to me. (Though I think it's better to use an immutable list, e.g. public static final List<String> strings = Collections.unmodifiableList(Arrays.asList("aa", "bb")).) This does not seem to me to be a good use of enum. Commented Mar 19, 2012 at 21:10

5 Answers 5

25

You can do

public static final String[] = {"aa", "bb"};

you just need to specify the name of the field:

public static final String[] STRINGS = {"aa", "bb"};

EDIT: I second Jon Skeet's answer that this is bad code practice. Anybody can then modify the contents of your array. What you can do is declare it private and specify a getter for the array. You will preserve the index-access and prevent accidental writes:

private static final String[] STRINGS = {"aa", "bb"};

public static String getString(int index){
    return STRINGS[index];
}

I guess you would need a method to get the length of the array as well:

public static int stringCount(){
    return STRINGS.length;
}

But as long as your project is small and you know what you are doing, you will be perfectly fine just leaving it public.

Sign up to request clarification or add additional context in comments.

8 Comments

Now anyone can write Foo.strings[0] = "haa haa";
This gives me an error llegal static declaration in inner class .. modifier 'static' is only allowed in constant variable declarations
@JonSkeet Yes that is correct. But then you could complain about storing the data directly in the code. I think the point of his assignment is to make it as simple as possible, not as correct as possible.
@JakubZaverka: I think when the question has a title about "constant array", it's a bad idea just to correct the syntax without any mention of why it's a bad idea.
@aGr: I wouldn't use either - an enum is more complicated than you need, and an array is mutable. I'd use Guava.
|
7

You can't create an immutable array, basically. The closest you can come is to create an immutable collection, e.g. with Guava.

public static final ImmutableList<String> SECRETS = ImmutableList.of(
    "George Tupou V, the King of Tonga, dies in Hong Kong at the age of 63.", 
    "Joachim Gauck is elected President of Germany.",
    "Lindsey Vonn and Marcel Hirscher win the Alpine Skiing World Cup.");

You could use an enum by giving each enum value an associated string, like this:

public enum Secret {
    SECRET_0("George..."),
    SECRET_1("Joachim..."),
    SECRET_2("Lindsey...");

    private final String text;

    private Secret(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

... but if you just want the strings as a collection, I'd use the immutable list. Enums are great when they're appropriate, but there's no indication that they're really appropriate in this case.

EDIT: As noted in another answer, this is perfectly valid:

public static final String[] FOO = {"aa", "bb"};

... assuming it's not in an inner class (which you didn't mention anywhere in your question). However, it's a very bad idea as arrays are always mutable. It's not a "constant" array; the reference can't be changed, but other code could write:

WhateverYourTypeIs.FOO[0] = "some other value";

... which I suspect you don't want.

3 Comments

It is possible to add parameters to enums.
@Legend: Yes (I was editing to demonstrate that), but then it's a collection of enums, not a collection of strings. If the OP just wants strings, I'd say this is overkill.
Instead of ImmutableList you can use native java List.of() introduced with java 9. It return an immutable list. Example : List.of("hello","hi","hey");
6
public enum Secret
{
    TONGA("George Tupou V, the King of Tonga, dies in Hong Kong at the age of 63."), 
    GERMANY("Joachim Gauck is elected President of Germany."),
    SKIING("Lindsey Vonn and Marcel Hirscher win the Alpine Skiing World Cup.");

    private final String message;

    private Secret(String message)
    {
        this.message = message;
    }

    public String getMessage()
    {
        return this.message;
    }
}

Comments

0
public enum NAMES {

  Mike("Mike Smith"),
  Peter("Peter Jones"),
  Tom("Thomas White"),
  Andy("Andrew Chu");

  private final String fullname;

  private NAMES(String value)
  {
    fullname = value;
  }
};

1 Comment

forgot closing ; for enum declaration
0

Insert the selected sentences in a Set<String> and then use the return value of Collections.unmodifiableSet(). Example:

final Set<String> mutableSentences = new HashSet<>();
/* ... */
final Set<String> sentences = Collections.unmodifiableSet(mutableSentences);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.