Using Java to implement a hash table (dictionary) with only arrays












1














I'm new to hash codes/hash tables, so I'm very unsure of my implementation. I want to create a hash table, but I can only use arrays. Specifically, I want to be able to insert things like a dictionary (a word and its meaning). Here is what I have:



public class HashTable {
String table;
int tableSize;

HashTable(int size) {
table = new String[size];
tableSize = size;
}

public void add(String key, String value) {

if (key == null || value == null) {
System.out.println("Cannot input null values");
}

int iter = 0;
int code = Math.abs(key.hashCode()) % tableSize;

if (table[code] == null) {
table[code] = new String{key, value};
} else {

while (table[code] != null) {
if (table[code][0].equals(key)) {
System.out.println("Already submitted submitted the word " + key);
return;
}

if (iter == tableSize) {
System.out.println("Table is full. Cannot add word "" + key + """);
return;
}

code++;
code %= tableSize;
iter++;
}

table[code] = new String{key, value};

}
}

public void remove(String key) {

if (key == null) {
System.out.println("Cannot input null value");
}

int iter = 0;
int code = Math.abs(key.hashCode()) % tableSize;

if (table[code][0].equals(key)) {
table[code] = null;
} else {
while (!table[code][0].equals(key)) {
if (iter == tableSize) {
System.out.println("Could not find word "" + key + """);
return;
}
code++;
code %= tableSize;
iter++;
}

table[code] = null;

}
}

public String get(String key) {

if (key == null) {
return "Cannot input null value.";
}

int iter = 0;
int code = Math.abs(key.hashCode()) % tableSize;

if (table[code][0].equals(key)) {
return table[code][1];
} else {
while (!table[code][0].equals(key)) {
if (iter == tableSize) {
return "Could not find word "" + key + """;
}
code++;
code %= tableSize;
iter++;
}

return table[code][1];

}
}

}


Is this an okay implementation? How can I make it better?



Thanks!










share|improve this question














bumped to the homepage by Community yesterday


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.




















    1














    I'm new to hash codes/hash tables, so I'm very unsure of my implementation. I want to create a hash table, but I can only use arrays. Specifically, I want to be able to insert things like a dictionary (a word and its meaning). Here is what I have:



    public class HashTable {
    String table;
    int tableSize;

    HashTable(int size) {
    table = new String[size];
    tableSize = size;
    }

    public void add(String key, String value) {

    if (key == null || value == null) {
    System.out.println("Cannot input null values");
    }

    int iter = 0;
    int code = Math.abs(key.hashCode()) % tableSize;

    if (table[code] == null) {
    table[code] = new String{key, value};
    } else {

    while (table[code] != null) {
    if (table[code][0].equals(key)) {
    System.out.println("Already submitted submitted the word " + key);
    return;
    }

    if (iter == tableSize) {
    System.out.println("Table is full. Cannot add word "" + key + """);
    return;
    }

    code++;
    code %= tableSize;
    iter++;
    }

    table[code] = new String{key, value};

    }
    }

    public void remove(String key) {

    if (key == null) {
    System.out.println("Cannot input null value");
    }

    int iter = 0;
    int code = Math.abs(key.hashCode()) % tableSize;

    if (table[code][0].equals(key)) {
    table[code] = null;
    } else {
    while (!table[code][0].equals(key)) {
    if (iter == tableSize) {
    System.out.println("Could not find word "" + key + """);
    return;
    }
    code++;
    code %= tableSize;
    iter++;
    }

    table[code] = null;

    }
    }

    public String get(String key) {

    if (key == null) {
    return "Cannot input null value.";
    }

    int iter = 0;
    int code = Math.abs(key.hashCode()) % tableSize;

    if (table[code][0].equals(key)) {
    return table[code][1];
    } else {
    while (!table[code][0].equals(key)) {
    if (iter == tableSize) {
    return "Could not find word "" + key + """;
    }
    code++;
    code %= tableSize;
    iter++;
    }

    return table[code][1];

    }
    }

    }


    Is this an okay implementation? How can I make it better?



    Thanks!










    share|improve this question














    bumped to the homepage by Community yesterday


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.


















      1












      1








      1







      I'm new to hash codes/hash tables, so I'm very unsure of my implementation. I want to create a hash table, but I can only use arrays. Specifically, I want to be able to insert things like a dictionary (a word and its meaning). Here is what I have:



      public class HashTable {
      String table;
      int tableSize;

      HashTable(int size) {
      table = new String[size];
      tableSize = size;
      }

      public void add(String key, String value) {

      if (key == null || value == null) {
      System.out.println("Cannot input null values");
      }

      int iter = 0;
      int code = Math.abs(key.hashCode()) % tableSize;

      if (table[code] == null) {
      table[code] = new String{key, value};
      } else {

      while (table[code] != null) {
      if (table[code][0].equals(key)) {
      System.out.println("Already submitted submitted the word " + key);
      return;
      }

      if (iter == tableSize) {
      System.out.println("Table is full. Cannot add word "" + key + """);
      return;
      }

      code++;
      code %= tableSize;
      iter++;
      }

      table[code] = new String{key, value};

      }
      }

      public void remove(String key) {

      if (key == null) {
      System.out.println("Cannot input null value");
      }

      int iter = 0;
      int code = Math.abs(key.hashCode()) % tableSize;

      if (table[code][0].equals(key)) {
      table[code] = null;
      } else {
      while (!table[code][0].equals(key)) {
      if (iter == tableSize) {
      System.out.println("Could not find word "" + key + """);
      return;
      }
      code++;
      code %= tableSize;
      iter++;
      }

      table[code] = null;

      }
      }

      public String get(String key) {

      if (key == null) {
      return "Cannot input null value.";
      }

      int iter = 0;
      int code = Math.abs(key.hashCode()) % tableSize;

      if (table[code][0].equals(key)) {
      return table[code][1];
      } else {
      while (!table[code][0].equals(key)) {
      if (iter == tableSize) {
      return "Could not find word "" + key + """;
      }
      code++;
      code %= tableSize;
      iter++;
      }

      return table[code][1];

      }
      }

      }


      Is this an okay implementation? How can I make it better?



      Thanks!










      share|improve this question













      I'm new to hash codes/hash tables, so I'm very unsure of my implementation. I want to create a hash table, but I can only use arrays. Specifically, I want to be able to insert things like a dictionary (a word and its meaning). Here is what I have:



      public class HashTable {
      String table;
      int tableSize;

      HashTable(int size) {
      table = new String[size];
      tableSize = size;
      }

      public void add(String key, String value) {

      if (key == null || value == null) {
      System.out.println("Cannot input null values");
      }

      int iter = 0;
      int code = Math.abs(key.hashCode()) % tableSize;

      if (table[code] == null) {
      table[code] = new String{key, value};
      } else {

      while (table[code] != null) {
      if (table[code][0].equals(key)) {
      System.out.println("Already submitted submitted the word " + key);
      return;
      }

      if (iter == tableSize) {
      System.out.println("Table is full. Cannot add word "" + key + """);
      return;
      }

      code++;
      code %= tableSize;
      iter++;
      }

      table[code] = new String{key, value};

      }
      }

      public void remove(String key) {

      if (key == null) {
      System.out.println("Cannot input null value");
      }

      int iter = 0;
      int code = Math.abs(key.hashCode()) % tableSize;

      if (table[code][0].equals(key)) {
      table[code] = null;
      } else {
      while (!table[code][0].equals(key)) {
      if (iter == tableSize) {
      System.out.println("Could not find word "" + key + """);
      return;
      }
      code++;
      code %= tableSize;
      iter++;
      }

      table[code] = null;

      }
      }

      public String get(String key) {

      if (key == null) {
      return "Cannot input null value.";
      }

      int iter = 0;
      int code = Math.abs(key.hashCode()) % tableSize;

      if (table[code][0].equals(key)) {
      return table[code][1];
      } else {
      while (!table[code][0].equals(key)) {
      if (iter == tableSize) {
      return "Could not find word "" + key + """;
      }
      code++;
      code %= tableSize;
      iter++;
      }

      return table[code][1];

      }
      }

      }


      Is this an okay implementation? How can I make it better?



      Thanks!







      java hash-table hashcode






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 '18 at 15:45









      user9597527user9597527

      61




      61





      bumped to the homepage by Community yesterday


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community yesterday


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
























          1 Answer
          1






          active

          oldest

          votes


















          0
















          • Do not special case an immediate success. The test for table[code] == null in



                if (table[code] == null) {
            table[code] = new String{key, value};
            } else {
            while (table[code] != null) {
            ....


            does not do anything useful, but only adds noise. Dive into the loop immediately.



            Ditto for table[code][0].equals(key) in remove and get.



          • Such low level utility functions shall not System.out.println (in any case, an error message shall go to System.err). Prefer returning an error code, and let the caller decide what to do.


          • It is unclear how well String.hashCode() is suited for this design of a hash table. Depending on the table size, you may get plenty of collisions. Using Math.abs on a hash code also biases the distribution. Need to measure.







          share|improve this answer





















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207236%2fusing-java-to-implement-a-hash-table-dictionary-with-only-arrays%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0
















            • Do not special case an immediate success. The test for table[code] == null in



                  if (table[code] == null) {
              table[code] = new String{key, value};
              } else {
              while (table[code] != null) {
              ....


              does not do anything useful, but only adds noise. Dive into the loop immediately.



              Ditto for table[code][0].equals(key) in remove and get.



            • Such low level utility functions shall not System.out.println (in any case, an error message shall go to System.err). Prefer returning an error code, and let the caller decide what to do.


            • It is unclear how well String.hashCode() is suited for this design of a hash table. Depending on the table size, you may get plenty of collisions. Using Math.abs on a hash code also biases the distribution. Need to measure.







            share|improve this answer


























              0
















              • Do not special case an immediate success. The test for table[code] == null in



                    if (table[code] == null) {
                table[code] = new String{key, value};
                } else {
                while (table[code] != null) {
                ....


                does not do anything useful, but only adds noise. Dive into the loop immediately.



                Ditto for table[code][0].equals(key) in remove and get.



              • Such low level utility functions shall not System.out.println (in any case, an error message shall go to System.err). Prefer returning an error code, and let the caller decide what to do.


              • It is unclear how well String.hashCode() is suited for this design of a hash table. Depending on the table size, you may get plenty of collisions. Using Math.abs on a hash code also biases the distribution. Need to measure.







              share|improve this answer
























                0












                0








                0








                • Do not special case an immediate success. The test for table[code] == null in



                      if (table[code] == null) {
                  table[code] = new String{key, value};
                  } else {
                  while (table[code] != null) {
                  ....


                  does not do anything useful, but only adds noise. Dive into the loop immediately.



                  Ditto for table[code][0].equals(key) in remove and get.



                • Such low level utility functions shall not System.out.println (in any case, an error message shall go to System.err). Prefer returning an error code, and let the caller decide what to do.


                • It is unclear how well String.hashCode() is suited for this design of a hash table. Depending on the table size, you may get plenty of collisions. Using Math.abs on a hash code also biases the distribution. Need to measure.







                share|improve this answer














                • Do not special case an immediate success. The test for table[code] == null in



                      if (table[code] == null) {
                  table[code] = new String{key, value};
                  } else {
                  while (table[code] != null) {
                  ....


                  does not do anything useful, but only adds noise. Dive into the loop immediately.



                  Ditto for table[code][0].equals(key) in remove and get.



                • Such low level utility functions shall not System.out.println (in any case, an error message shall go to System.err). Prefer returning an error code, and let the caller decide what to do.


                • It is unclear how well String.hashCode() is suited for this design of a hash table. Depending on the table size, you may get plenty of collisions. Using Math.abs on a hash code also biases the distribution. Need to measure.








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 8 '18 at 19:17









                vnpvnp

                38.6k13097




                38.6k13097






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207236%2fusing-java-to-implement-a-hash-table-dictionary-with-only-arrays%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to make a Squid Proxy server?

                    第一次世界大戦

                    Touch on Surface Book