如何在Java中存储常量字符串数组

时间:2012-03-19 21:07:42

标签: java enums const

我在应用程序中从一组特定字符串中随机选择。我将这些数据直接存储在代码中。据我所知,你不能声明public static final String[] = {"aa", "bb"}。所以我虽然enum会很有用,但对于单字名称可以正常工作:

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

但是如何存储这样的句子呢?这里的枚举失败了:

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.";
}

我还应该使用什么?或者我错误地使用枚举?

5 个答案:

答案 0 :(得分:20)

你可以做到

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

您只需指定字段的名称:

public static final String[] STRINGS = {"aa", "bb"};
编辑:我是Jon Skeet的第二个回答,这是不好的代码练习。然后任何人都可以修改数组的内容。你可以做的是声明它是私有的并为数组指定一个getter。您将保留索引访问并防止意外写入:

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

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

我想你需要一个方法来获得数组的长度:

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

但是只要你的项目很小并且你知道自己在做什么,你就可以将它公之于众。

答案 1 :(得分:6)

基本上你不能创建一个不可变数组。你最接近的是创建一个不可变的集合,例如与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.");

可以使用enum,为每个枚举值提供一个相关的字符串,如下所示:

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;
    }
}

...但如果只是希望将字符串作为集合,我会使用不可变列表。当它们合适时,枚举很好 ,但没有迹象表明它们在这种情况下非常合适。

编辑:如另一个答案中所述, 完全有效:

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

...假设它不在内部类(你在问题的任何地方没有提到)。然而,这是一个非常糟糕的想法,因为数组总是可变的。它不是一个“常数”阵列; 引用无法更改,但其他代码可以写:

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

...我怀疑你不想要。

答案 2 :(得分: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;
    }
}

答案 3 :(得分: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;
  }
};

答案 4 :(得分:0)

Set<String>中插入所选句子,然后使用Collections.unmodifiableSet()的返回值。例如:

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