0

I'm trying to use Hashmap in Java 8. I will use the hash function to get the index to put the node with given key and value. However, if there are nodes with the same key, I have to use Linked List kind of data structure. This is where I'm confused about.

For example, if there are

package First;

import java.util.HashMap;

public class MyClass extends Node {
  public MyClass(int k, int v) {
        super(k, v);
        // TODO Auto-generated constructor stub
    }

public static void main(String[] args) {
    HashMap<String, Node> capitalCities = new HashMap<String, Node>();
    capitalCities.put("England", new Node(1,3));
    capitalCities.put("Germany", new Node(1,3));
    capitalCities.put("Norway", new Node(1,3));
    capitalCities.put("USA", new Node(1,3));
    capitalCities.put("USA", new Node(1,3));
    System.out.println(capitalCities); 
  }
}

If I print h1, it will only have "APPLE", 13 So I want to make the Hashmap to be like this: "APPLE", 1 -> "APPLE", 10 -> "APPLE", 13

  • actually, the code you posted will throw an NullPointerException. How do you try to print h1? – Stultuske Jun 10 '20 at 05:40
  • I just posted some scratch code Now I edited and put the real code I'm testing out – Minjae Rhee Jun 10 '20 at 05:47
  • The original code you posted will only print one, because they all had the same key. The code you have now will (obviously) not print 'APPLE', it will print the last element of USA, the Norway element and the Germany and England elements. – Stultuske Jun 10 '20 at 05:59
  • The main thing I want to do is insert "USA", "NY" and "USA", "DC" (for example). Is there any way to insert objects with same key? – Minjae Rhee Jun 10 '20 at 06:05
  • no. if you add a second element with the same key, it overwrites it. You can first get an existing element of the key, then merge the object that's already there, and the one you want to add, and put that for that key – Stultuske Jun 10 '20 at 06:10
  • But when I search about the hashmap, I saw an image that shows more than one object can be stored at the same index.So that is actaully not possible to do in hashmap ? – Minjae Rhee Jun 10 '20 at 06:16
  • nobody is stopping you from making the value a list and instead of putting for duplicate keys, just adding to the list – Stultuske Jun 10 '20 at 06:17
  • Does that mean I have to use the linked list? or a general list? I am trying to make a Hashtable with chaining? I think that's what it's called – Minjae Rhee Jun 10 '20 at 07:57

1 Answers1

0

String class hashcode and equal methods make "APPLE" unique. So, you need to put the object as a key or Use StringBuilder instead of String. Like below

Map<StringBuilder, Integer> h1 = new HashMap<>();
h1.put(new StringBuilder("APPLE"), 1);
h1.put(new StringBuilder("APPLE"), 10);
h1.put(new StringBuilder("APPLE"), 13);
System.out.println(h1);