0

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; 
1
  • 2
    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. Commented Mar 17, 2019 at 17:55

3 Answers 3

1

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 );
Sign up to request clarification or add additional context in comments.

Comments

0

Use:

private myHash<Integer, List<Integer>> data; 

Comments

0
if(data.containsKey(123)
  {
    data.get(123).add(Object)
  }
 else
  {
    data.put(KeyValue,Object)
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.