Dictionary.java 1.86 KB
Newer Older
Michele Fiori's avatar
Michele Fiori committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
package beans;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashMap;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Dictionary {

    @XmlElement(name = "dictionary")
    private HashMap<String, String> dictionary;

    private static Dictionary instance;

    public Dictionary(){
        dictionary = new HashMap<String, String>();
    }
    public Dictionary(HashMap<String, String> dict){
        dictionary = dict;
    }

    //See the singleton pattern
    public synchronized static Dictionary getInstance(){
        if(instance==null){
            instance = new Dictionary();
        }
        return instance;
    }

    public int addWord(String w, String d){
        synchronized (this) {
            if (dictionary.containsKey(w)) {
                return -1;  //Key is already presnet
            } else {
                dictionary.put(w, d);
                System.out.println("Added word: " + w + "; Definition: " + dictionary.get(w));
                return 0;
            }
        }
    }

    public int changeWordDefinition(String w, String d){
        synchronized (this) {
            if (!dictionary.containsKey(w)) {
                return -1;  //Key is not present
            } else {
                dictionary.replace(w, d);
                return 0;
            }
        }
    }

    public String viewDefinition(String w){
        if(!dictionary.containsKey(w)){
            System.out.println("Definition of " + w + " not found");
            return null;
        }else{
            System.out.println("Definition of " + w + ": " + dictionary.get(w));
            return dictionary.get(w);
        }
    }

    public void deleteWord(String w){
        dictionary.remove(w);
    }

}