diff --git a/chapter-3/3.5-java/Markov.java b/chapter-3/3.5-java/Markov.java index 984f3c1..f719bde 100644 --- a/chapter-3/3.5-java/Markov.java +++ b/chapter-3/3.5-java/Markov.java @@ -55,8 +55,8 @@ public void generate(int words) { if (suf.equals(NON_WORD)) break; System.out.print(suf + " "); - prefix.pref.removeElementAt(0); - prefix.pref.addElement(suf); + prefix.pref[0] = prefix.pref[1]; + prefix.pref[1] = suf; } } @@ -67,8 +67,8 @@ public void add(String word) { statetab.put(prefix.clone(), suf); } suf.addElement(word); - prefix.pref.removeElementAt(0); - prefix.pref.addElement(word); + prefix.pref[0] = prefix.pref[1]; + prefix.pref[1] = word; } } @@ -76,33 +76,33 @@ class Prefix { private static final int MULTIPLIER = 31; - public Vector pref; + public String[] pref; public static Prefix from(Integer size, String value) { Prefix p = new Prefix(); - p.pref = new Vector<>(); + p.pref = new String[size]; for (int i = 0; i < size; i++) - p.pref.add(value); + p.pref[i] = value; return p; } public Prefix clone() { Prefix n = new Prefix(); - n.pref = (Vector) this.pref.clone(); + n.pref = this.pref.clone(); return n; } public int hashCode() { int h = 0; - for (int i = 0; i < pref.size(); i++) - h = MULTIPLIER * h + pref.elementAt(i).hashCode(); + for (int i = 0; i < pref.length; i++) + h = MULTIPLIER * h + pref[i].hashCode(); return h; } public boolean equals(Object o) { Prefix p = (Prefix) o; - for (int i = 0; i < pref.size(); i++) - if (!pref.elementAt(i).equals(p.pref.elementAt(i))) + for (int i = 0; i < pref.length; i++) + if (!this.pref[i].equals(p.pref[i])) return false; return true; } diff --git a/chapter-3/3.5-java/README.md b/chapter-3/3.5-java/README.md index 716a6ff..28b9734 100644 --- a/chapter-3/3.5-java/README.md +++ b/chapter-3/3.5-java/README.md @@ -8,4 +8,10 @@ - Remove use of deprecated constructor of `StreamTokenizer` - Static constructor, instead of constructors with fields that differ from the fields of the class -Changes applied in [this commit](https://github.com/asankov/the-practice-of-programming/commit/793994dae973f3d4d9a14224fb511f9d6fe9de82). \ No newline at end of file +Changes applied in [this commit](https://github.com/asankov/the-practice-of-programming/commit/793994dae973f3d4d9a14224fb511f9d6fe9de82). + +#### Exercise 3-4 +Revise the Java version of `markov` to use an array instead of a `Vector` for the prefix in the `State` class. + +*Answer:* An array makes more sense than `Vector`, because the size is fixed and known when the object is instantiated. +Therefore, we don't need data struct that can grow and shrink dinamically. \ No newline at end of file