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 9 years ago.
Improve this question
Is order still guaranteed when the map objects are accessed as shown below at location 1 and 2?
//....
public void firstMethod(){
Map<K,V> sortedMap=new LinkedHashMap<K,V>();
sortedMap.put(h,g);
//....
Map<K,V> anotherMap=someOtherMethod(sortedMap);
// order of anotherMap when read ...2
}
public Map<K,V> someOtherMethod(Map<K,V> someMap){
someMap.put(a,b);
//order of someMap when read ...1
//.....
return someMap;
}
//....
If the concrete instance of your Map object is a LinkedHashMap yes. It does not matter what you do with it. The object will keep it's data ordered and the implementation does not change if you cast to just Map or even Object or pass it to methods. It will stay internally a LinkedHashMap. You might no longer see that it is one if you cast it to Object.
Assuming that you don't know the source code, the only thing that is not guaranteed is that someOtherMethod returns your LinkedHashMap. It could also re-order it.
A method should not be trusted unless it specifies those things. But since you know the sourcecode here, you have the guarantee that it is your LinkedHashMap in perferct order.
As per the docs:
Hash table and linked list implementation of the Map interface, with predictable iteration order.
So even after things are inserted and removed, the order should persist through whatever you want to do to it.
Related
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 1 year ago.
Improve this question
I have more enums with some values and I want asked you what the method is good to cache enum values:
For example:
public enum Animal {
Dog, Cat, Cow;
static Animal[] values;
static EnumSet<Animal> cachedAnimalsEnumSet;
static List<Animal> cachedAnimalsList;
static {
values = values();
cachedAnimalsEnumSet = EnumSet.allOf(Animal.class);
cachedAnimalsList = Arrays.asList(Animal.values());
}
}
Which is the best way:
values, cachedAnimalsEnumSet or cachedAnimalsList ?
Assuming that your purpose of caching is to avoid creation of new array every time anyone calls Animal.values(), and instead just use the cached value. I'd recommend using EnumSet for following reasons:
All basic operations are constant time.
There is not point in caching duplicate enum values, and the Set implementation takes care of it for you.
However, couple things to consider are that null values are not allowed in EnumSet (highly doubt you want to cache nulls). And second thing to be careful about is that EnumSet is not synchronized. So if you are going to have multiple threads access, and modify this cache, you'd have to wrap it using Collections.synchronizedSet method.
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 3 years ago.
Improve this question
I know the underlying difference between the remove() method of the traditional collection like hashMap and concurrent collection like concurrentHashMap. In concurrentHashmap, JVM will match the key and the value both before removing the key value object which is required for the multithreading environment.
Is there any other difference between them?
I think you are asking why is there a second remove method in the concurrent map.
Map has:
V remove(Object key)
ConcurrentMap has an additional method:
boolean remove(Object key, Object value)
(In fact, Map has this as a default method since 1.8.)
In a non-concurrent Map, the two-arg form can easily written by composing a get followed by remove, at the cost of two lookups. Concurrent operations, however, do not compose. For concurrent maps you may see remove used in a loop similar to how compareAndSet is typically used.
You could perform the remove operation in a single operation through the normal collections interfaces if you first used entrySet. It's just not very convenient or obvious.
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 5 years ago.
Improve this question
I'm using an HashMap<Integer, MyObject> collection to store a list of few couples of values.
Is it safe use Integer as key? the behavior is the same both on put and get method?
yes it's safe. Integer is just a wrapper class for int.
i know this from own experience. created a captcha functionality that way. (user requests a random integer. my prog creates a captcha-pic and saves the answer[value] and random integer id[key] in a hashmap. btw if you want to create a "cache" use java's LinkedHashMap. it has a protected boolean method called "removeEldestEntry(Map.Entry eldest)" which is called during a put-event. if you override it with, eg "return size() > MAX_SIZE;" it will delete the oldest entry (or the entry based on oldest access - there's an option in the constructor) if the condition you provided returns true). hope this helped. :/
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 9 years ago.
Improve this question
I've been thinking about the naming of three methods in the famous Map class. To get all keys in the map we use keySet(), for entries there is entrySet() and for values the values() method is used.
What I find a bit peculiar is that the first two methods includes the returned type (set) in the name. Wouldn't it be nicer to exclude it? That would mean that the method names would be harmonized and it would look quite nice (imho!):
keys()
entries()
values()
The other alternative would be to suffix the values() method:
keySet()
entrySet()
valueCollection()
To me this doesn't look as good and makes the code ugly.
This is a philosophical question as changing the method naming would break the backward compatibility.
Any thoughts on the topic?
The main intention of having the Set is to signify that the returned collection would have the characteristics of Set (i.e) it will not contain any duplicates.
And since values() like the others, returns a Collection(mind you, keySet and entrySet also return a collection, but a specific one, Set), it would quite trivial to include the collection word in the method name.
Keeping method names as keySet or entrySet shows your intent that you are returning a Set and committing to the characteristics of Set namely no duplicates.
On keeping names as keys or entries you should return a Collection or Iterable so that shows the intent that the implementation has not committed to any particular type of Collection and that may change in future.
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 9 years ago.
Improve this question
Can anybody tell me the reason why HashMap doesn't implement the Iterable interface?
To be blunt, Map in general (and HashMap in particular) do not implement Iterator because it is not clear what it should be iterating. There are three choices:
Keys
Values
Entries
None of the three choices above look entirely unreasonable: an argument can be made in favor of each of these approaches. In the end, the library designers decided not to make this choice for you, letting programmers pick what to iterate explicitly.
Map doesn't implement it but you can use keySet() or values() or entrySet() and all implement iterator as they are sets. See Map javadoc here
Hash map contains two data structures, keys and values, and each of them has an iterator.
HashMap as a whole is not a data structure that you should iterate over.
Not directly. You need a 1 dimension structure to iterate it.
hashMap.entrySet().iterator() will do the job.
Sun could have made Map extend Iterable, but that would require that Map itself should have an iterator() method. Imagine all the custom Map implementations that would be broken. It's bad enough they did that with the java.sql interfaces.
Besides, you can iterate over the map by using keySet(), entrySet() or values() - that's 8, 10 or 8 extra characters.
Map interface does not implement Collection interface, because it does not contain elements but contains entries of keys and their corresponding values.