有 Java 编程相关的问题?

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

java在任意事物的列表(数组)中创建关联的最佳方法是什么?

我正在制作一个单词定义测验应用程序,我的单词列表和它们的定义是JSON格式的,结构如下:

"words": [
        {
            "word": "rescind",
            "type": "verb",
            "definition": "to take back, repeal as in a rule or policy"
        },
        {
            "word": "curtail",
            "type": "verb",
            "definition": "to reduce or lessen"
        },

等等等等

在测验中,你会得到一个随机挑选的单词和五个可供选择的定义。就像标准化的多项选择题

现在,我开始发现一个问题,我有一些意思非常相似的词。目前,我从列表中随机选择了4个错误的定义,但为了避免混淆,我希望避免选择与正确选择类似的定义

我应该如何创建这个“相似性”地图?我想到的一个解决方案是:

        {
            "word": "avid",
            "type": "adjective",
            "definition": "extremely excited about, enthusiastic about",
            "similar to": [
                "ardent",
                "fervent"
            ]
        },

但我意识到这个解决方案有点糟糕,因为我必须找到每个单词并实现同一个列表,当我最后添加很多单词时,它会变得很难编辑

你们认为什么是最好的解决方案


共 (1) 个答案

  1. # 1 楼答案

    第一种简单的方法是创建一个带有字段的Word

    确保使用“word”字段覆盖^{}^{}(我调用dit“value”以将其与类名区分开来)(见下文):

    public class Word {
        private final String value;
        private final String type;
        private final String definition;
        private final List<Word> synonymns = new ArrayList<Word>();
    
        public Word(String value, String type, String definition) {
            this.value = value;
            this.type = type;
            this.definition = definition;
        }
    
        // equals() and hashCode() based on the value field
        @Override
        public int hashCode() {
            return value.hashCode();
        }
        @Override
        public boolean equals(Object obj) {
             return obj instanceof Word && ((Word)obj).value.equals(value);
        }
    
        public String getValue() {
            return value;
        }
        public String getType() {
            return type;
        }
        public String getDefinition() {
            return definition;
        }
        public List<Word> getSynonymns() {
            return synonymns;
        }
    }
    

    基于值字段实现equals()hashCode()意味着您可以通过使用以下集合来防止重复:

    Set<Word> words = new HashSet<Word>(); // wont allow two Word objects with the same value
    

    您可以使用来自^{}的返回值(如果集合中尚未包含指定的元素,则返回值为true)来检查所添加的单词实际上是唯一的:

    Word word = new Word("duplicate", "adjective", "another copy");
    if (!words.add(word)) {
        // oops! set already contained that word
    }
    

    如果你想添加特殊的酱汁,请将type作为枚举:

    public enum PartOfSpeach {
        NOUN,
        VERB, // in USA "verb" includes all nouns, because any noun can be "verbed"
        ADJECTIVE,
        ADVERB
    }
    

    你可以考虑允许单词属于多种类型:

    • 吠叫:动词:狗做什么
    • 树皮:名词:什么覆盖着一棵树
    事实上,你可以考虑每个词有多重含义:

    public class Meaning {
        PartOfSpeach p;
        String definition;
        List<Word> synonyms; // synonyms belong to a particular *meaning* of a Word.
    }