0
votes

I´m traying to add a value inside an array of values when the key of my hash table is repeated. For example,

Key1 = 123 || Value1 = 23

Key2 = 123 || Value2 = 56

So when I´m done adding my elements, I expect something like

Key1 ==> [23,56]

I have initialized my hash table like this

private myHash<Integer, myObject[]> data; 
3
You can't ad a value to an array. You can make a larger copy of the array and store the new one in the map, but why not use a List instead? Read the Java tutorial on collections. Avoid arrays in general. - JB Nizet

3 Answers

1
votes

Best approach is a Map of Integer as Key and a List as Value. Like this:

// This is a member, meaning it's on class level.
private Map<Integer, List<Integer>> myHashMap = new HashMap<>();

// Now populate..  e.g. Key=123,  Value 23
private addValueForKey(Integer key, Integer value) {
  List<Integer> values = myHashMap.get( key );
  if (values == null) {
    values = new ArrayList<Integer>();       
  }

  values.add( value );
}

Now each time you want to add a value to your hashmap, just call the method. for example:

addValueForKey( 123, 23 );
addValueForKey( 123, 56 );
0
votes

Use:

private myHash<Integer, List<Integer>> data; 
0
votes
if(data.containsKey(123)
  {
    data.get(123).add(Object)
  }
 else
  {
    data.put(KeyValue,Object)
  }