What are the pros and cons of LinkedHashMaps vs. LinkedHashSets?

soldier.moth picture soldier.moth · Jun 10, 2009 · Viewed 12k times · Source

Could someone explain the main benefits for choosing one over the other and the detriments that come with that choice?

Answer

Benson picture Benson · Jun 10, 2009

They solve different problems, LinkedHashMap does a mapping of keys to values, a LinkedHashSet simply stores a collection of things with no duplicates.

A linked hash map is for mapping key/value pairs -- for example, storing names and ages:

Map<String,Integer> namesAndAges = new LinkedHashMap<String,Integer>();
namesAndAges.put("Benson", 25);
namesAndAges.put("Fred", 19);

On the other hand, a linked hash set is for storing a collection of one thing -- names, for example:

Set<String> names = new LinkedHashSet<String>();
names.add("Benson");
names.add("Fred");