gpt4 book ai didi

java - 我可以创建集合数组吗?

转载 作者:行者123 更新时间:2023-12-01 18:40:24 25 4
gpt4 key购买 nike

这就是我正在尝试做的事情。

我正在阅读一个单词列表,每个单词都有一定的复杂程度。每行都有一个单词,后跟一个逗号和单词的级别。例如“ watch ,2”。我希望将给定级别的所有单词放入一个集合中,以确保它们在该级别中的唯一性。复杂度有 5 个级别,因此理想情况下我想要一个包含 5 个元素的数组,每个元素都是一个集合。

然后,我可以在读入单词时将单词添加到每个集合中。稍后,我希望提取指定级别的随机单词。

除了如何创建集合数组之外,我对一切都很满意。我在这里阅读了其他几篇文章,这些文章似乎同意这不能完全按照我希望的方式完成,但我找不到好的解决方法。 (不,我不愿意在 switch 语句中包含 5 个集合。这违背了规律。)

谢谢。

最佳答案

您可以使用 map 。使用级别作为键,使用值作为包含单词的集合。这将帮助您提取给定级别的值,当从某个级别请求随机单词时,使用该级别的键获取值(在本例中设置)并从中选择一个随机值。如果您增加级别数量,这也会扩展

public static void main(String[] args) {
Map<Integer, Set<String>> levelSet = new HashMap();
//Your code goes here to get the level and word
//
String word="";
int level=0;
addStringToLevel(levelSet,word,level);

}

private static void addStringToLevel(Map<Integer, Set<String>> levelSet,
String word, int level) {
if(levelSet.get(level) == null)
{
// this means this is the first string added for this level
// so create a container to hold the object
levelSet.put(level, new HashSet());
}

Set<String> wordContainer = levelSet.get(level);
wordContainer.add(word);
}

private static String getStringFromLevel(Map<Integer, Set<String>> levelSet,
int level) {
if(levelSet.get(level) == null)
{
return null;
}

Set<String> wordContainer = levelSet.get(level);
return "";// return a random string from wordContainer`
}

关于java - 我可以创建集合数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20128160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com