How do Treemaps handle collisions in java? [duplicate] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have the below code for tree map where I store duplicate key and it seems overwrite the existing one.
TreeMap<String, Integer> tm=new TreeMap<>();
tm.put("vivek", 1);
tm.put("vivek", 2);
System.out.println(tm);
It prints {vivek=2} So it means map allow to overwrite on key basis?

All maps share the same basic properties, one of which is that all keys must be unique. Hence why keySet() returns a Set.
To do what you are looking for you need a Multimap - which is essentially a Map to a List.
Map<Integer, List<String>> multiMap;
To add an object get the list for that key, if it is null add a list then add your value to the list, otherwise just add your value to the existing list.
There are some multimap implementation available in various 3rd party libraries or it's easy enough to implement your own.

TreeMap#public V put(K key, V value) API says
Associates the specified value with the specified key in this map.
If the map previously contained a mapping for the key, the old value is replaced.

Related

Why is adding an entry set as parameter to addall method a bad practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
Why is the following code a bad practice and what is the solution for it?
TreeSet<Map.Entry<Integer, Map<String, String>>> sortedtable = new TreeSet<>(new ComparatorByDueDate());
public void sortTable(Map<Integer, Map<String, String>> table){
sortedtable.addAll(table.entrySet());
}
Update: As per Sonar, it is a bad practice. I am asking the question here as the sonar explanation seems confusing.
Java Map.Entry objects are not intended for long term storage. From the docs (emphasis mine),
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.
If anyone, for any reason, adds, removes, or modifies any part of the map after the fact, then your TreeSet entries now have undefined behavior. They might still be good, they might get nulled out, they might exhibit some random behavior.
If you want to store a pair of elements, then write a class that has two instance variables. If you're on a new enough Java version, then records are great for this sort of thing.

Hashmaps - using booleans [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was implementing a Java program containing hash maps, I wanted to use two different hash-maps and a boolean function. So for every key, depending on the boolean outcome, it would select one of the hash-maps. What would be some disadvantages/advantage of this?
There are two ways to do this (as far as I can think of at the moment):
Method 1: (from #WJS in the comments)
Have a HashMap with a boolean key and the corresponding HashMap as the value. Like so:
HashMap<Boolean, Map<Key, Value>> outer = new HashMap<>();
Method 2:
Since there can only be two HashMaps corresponding to your boolean true or false value, I don't think you need to have another HashMap and can simply use a boolean variable.
For Example:
// or similar depending on your implementation and needs; can be
// extended for choosing get(), set(), etc.
boolean flag;
HashMap<Key, Value> trueMap = new HashMap<>();
HashMap<Key, Value> falseMap = new HashMap<>();
HashMap<Key, Value> map = flag ? trueMap : falseMap;
There is no downside to having HashMaps chosen like this and is actually fairly common.

What type of object is returned when keySet() method of HashMap is called in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
From the documentation, it returns Set<E> which is an interface. Suppose I write this,
Set<E> keys = myHashMap.keySet();
I do not understand what exactly is returned by this keySet() or what are the variable keys.
Also, why am I able to do this
Iterator<E> it = keys.iterator();
as interfaces do not implement any of its methods.
According to java doc,
Map.keyset() Returns a set view of the keys contained in this map. The
set is backed by the map, so changes to the map are reflected in the
set, and vice-versa. If the map is modified while an iteration over
the set is in progress (except through the iterator's own remove
operation), the results of the iteration are undefined.
so basically it is an object of a class which implements Set Interface that's why we are able to call iterator() on that object.
HashMap.keySet() returns set of the keys in the hash map.
HashMap<Integer, String> myHashMap = new HashMap<>();
myHashMap.put(1, "one");
myHashMap.put(2, "two");
myHashMap.put(3, "three");
Set<Integer> keys = myHashMap.keySet();
System.out.println("keys of the map are: "+keys); // prints [1, 2, 3]
Also, Set<E> extends Collection<E>, which also extends Iterable<E>. That means Iterable<E> is a superinterface of Set<E> That's why you are able to do iterator() from Set<E>
myHashMap.keySet() returns a Set view of the keys contained in this map myHashMap.
Remember that Map is different from Set such that:
Map consists of key and value pair. A Key is mapping to a specific value.
Set consists only on individual objects of any type. They aren't stored in pairs.
see the documentation.
What is an iterator then?
If you will want to cycle through the elements in a collection, For example, you might want to display each element. In our case, if you want to display each key in the set that's returned, then we'd use the iterator.
Iterator enables you to cycle through a collection, obtaining or removing elements.

TreeMap and LinkedHashMap classes [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I found a Java question J couldn't understand what should be answer
The TreeMap and LinkedHashMap classes:
enable iteration of a map's entries based on the insertion order of elements only.
enable iteration of a map's entries based on natural ordering of keys only.
enable iteration of a map's entries in a deterministic order.
enable iteration of a map's entries based either natural ordering of keys OR natural ordering of values depending on the arguments sent to the contructor.
In Java:
TreeMap is a Map that automatically sorts the Map entries according to its natural ordering using Comparable<T> interface
LinkedHashMap is Map that guarantees that the entries will be returned in the same order as they were added

Adding data to a collection with unbounded wildcard type [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
What is the difference between the two? Why can't I add data to the first one, but can add to the second one?
HashMap<?, Object> map = new HashMap<>();
map.put(Integer.class, 1); // Error
HashMap<Class<?>, Object> map2 = new HashMap<>();
map2.put(Integer.class, 1); // Ok
In first case, the type of keys is any concrete (i.e. the same for all keys of map), so we can't insert anything except null, because we don't know this type. (So map can hold a value of type HashMap<Integer, Object> or HashMap<String, Object> or else).
In second case, the type of keys is Class with any concrete type-argument, that may differ from one key to another. So you cat put into this map a key-value pair, where key is any instance of Class (Class<Integer>, Class<String>,...), but you can't put keys with other types (for example, Integer, String,...)
Go through this tutorial,this might help you understand wild cards and their uses.
http://ted-gao.blogspot.co.uk/search/label/Java%20Generics
and for difference between List and map ::
Java map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
Java list: An ordered collection (also known as a sequence).The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Categories