有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HashMap get方法看起来像是在返回一个副本,对吗?

我有一个程序,可以逐字读取包含小故事的文本文件。检查每个单词是否有“<;名词>;”形式的标签,“<;动词>;”或者类似的东西。如果找到标签,它将使用与标签对应的ArrayList中的随机字替换该标签,方法如下:

private String getSubstitute(String label) {
        if (listMap.get(label) != null){
            String substitute = randomFrom(listMap.get(label));
            listMap.get(label).remove(substitute);
            return randomFrom(listMap.get(label));
        }
        if (label.equals("number")){
            return " " + myRandom.nextInt(50) + 5;
        }
    return "**UNKNOWN**";
}

这是相当好的工作,除了在每一个单词的使用,它应该从它的相应列表中删除,这样它就不能被重复使用。我试着在上面代码的第4行中这样做。HashMaplistMap<String, ArrayList>是一个实例变量,所以我觉得调用 listMap.get(label).remove(substitute),我将直接访问listMap中包含的ArrayList并将其删除。但是,当我运行代码时,有时会看到以前使用过的单词重复出现。我错过了什么

举个有趣的例子,下面是在一个实例中打印出来的内容:

This is a slippery story about how a blue tiger became a blue tiger. Once upon a time, about 295 decades ago, angry, angry pangolins roamed the earth. One of them was named Jermaine. This pangolin was alone in the world. Then it became a orange pangolin living in Ecuador. This animal loved to think and surrender. In the morning it would eat a green fig, and later eat a angry mango for a snack.

这是这个故事产生的文本文件:

This is a <adjective> story about how a <color> <animal> became a <color> <animal>. Once upon a time, about <number> <timeframe> ago, <adjective>, <adjective> <animal>s roamed the earth. One of them was named <name>. This <animal> was alone in the world. Then it became a <color> <animal> living in <country>. This animal loved to <verb> and <verb>. In the morning it would eat a <color> <fruit>, and later eat a <adjective> <fruit> for a snack.


共 (3) 个答案

  1. # 1 楼答案

    问题是,您肯定会删除分配给substitute的那个。但你不能退回那个。你可以随机返回另一个。所以你没有移除你返回的那个

    应该是的

        private String getSubstitute(String label) {
            if (listMap.get(label) != null){
                String substitute = randomFrom(listMap.get(label));
                listMap.get(label).remove(substitute);
                return substitute;
            }
            if (label.equals("number")){
                return " " + myRandom.nextInt(50) + 5;
            }
            return "**UNKNOWN**";
         }
    
  2. # 2 楼答案

    你不能删除getSubstitute返回的内容。您将返回最后生成的下一个随机单词:

    return randomFrom(listMap.get(label));

  3. # 3 楼答案

    5号线

    return substitute;
    

    而不是

    return randomFrom(listMap.get(label));