Node.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package fr.pavnay.scrabble;
  2. import java.io.Serializable;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. public class Node implements Serializable {
  7. private static final long serialVersionUID = 3539215265338287172L;
  8. private Node[] nodes = new Node[26];
  9. private List<String> words;
  10. private String parent;
  11. public Node(String parent) {
  12. this.parent = parent;
  13. }
  14. public void addWord(String word) {
  15. if (this.words == null) {
  16. this.words = new ArrayList<String>();
  17. }
  18. if (!this.words.contains(word)) {
  19. this.words.add(word);
  20. }
  21. }
  22. public List<String> getWords() {
  23. if (this.words == null) {
  24. return null;
  25. }
  26. Collections.sort(this.words);
  27. return this.words;
  28. }
  29. public Node getNode(char character) {
  30. Node node = this.nodes[(character - 'a')];
  31. if (node == null) {
  32. node = new Node(this.parent + character);
  33. this.nodes[(character - 'a')] = node;
  34. }
  35. return node;
  36. }
  37. public int getWordsCount() {
  38. int total = 0;
  39. for (int i = 0; i < 26; i++) {
  40. Node current = this.nodes[i];
  41. if (current != null) {
  42. total += current.getWordsCount();
  43. }
  44. if (this.words != null) {
  45. total += this.words.size();
  46. }
  47. }
  48. return total;
  49. }
  50. public String toString() {
  51. StringBuilder sb = new StringBuilder("Parent " + this.parent);
  52. if (this.words != null) {
  53. sb.append(this.words.toString());
  54. } else {
  55. sb.append('-');
  56. }
  57. for (int i = 0; i < 26; i++) {
  58. Node current = this.nodes[i];
  59. if (current != null) {
  60. sb.append(current);
  61. }
  62. }
  63. return sb.toString();
  64. }
  65. }