Method naming in Map class: keySet(), entrySet() and values() [closed] - java

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.

Related

Why does Java not implement a last() method for ArrayLists? [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 3 years ago.
Improve this question
I am not asking how to find it, that is already answered in this other question:
But just going deeper into data-structures in Java, I have found out that the LinkedList implementation has a getLast() method that is not implemented (I suppose for some reason) in the ArrayList implementation. I could not find any other similar question nor post on Internet explaining it, so I decided to ask it here.
We may agree that it is not elegant the current way of getting the last element from an ArrayList, and usually this implementation is more widely used than LinkedList because it performs better in a wider range of scenarios, as discussed here.
Does anybody know why ArrayList does not implement that method?
Edit: I have edited my question to avoid confusion and opinion based answers. The answer below from Andreas is the one I was looking for, based on facts and references.
The Collection classes generally don't implement any public methods that aren't specified by an interface.
ArrayList does have one method named trimToSize() that isn't specified by an interface, but that is a very implementation-specific method.
LinkedList doesn't have any methods that isn't specified by an interface.
The reason LinkedList has a getLast() is shown in the javadoc:
Specified by:
getLast in interface Deque<E>
Deque has most of the same methods as List does. The main difference is that List has methods for accessing elements by index position, while Deque has methods for accessing first / last element.
If you want to work with a list-like collection structure where access to the last element is simple, code to the Deque interface, not the List interface, and use ArrayDeque instead of ArrayList.
You can access an ArrayList last element with a simple ArrayListName.get(ArrayListName.size() - 1); because you can access an ArrayList element directly with it's index, however in a linked list you have to iterate through every element before you're able to access the last element, this is [most probably] why the engineers created a method to access the last element of a linked list.

What is the advantage of remove() method in traditional collection and concurrent collection 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 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.

Can ThreadLocal be used as Key in HashMap? [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 5 years ago.
Improve this question
Can ThreadLocal be used as Key in HashMap?
If so, how does it work and is it generally a bad idea? What should I look out for and be aware of?
You can use ThreadLocal as a HashMap key like any other object. Whether it has any meaning is a different topic.
Basically you can have problems if you use a mutable object as a key for things like HashMap, HashSet and so on, because those classes usually use hashCode() (hence the name) to put stuff in buckets and retrieve it. So if you use a mutable object as a key, then change the object (in a way the hashCode changes) and then try to retrieve the entry by key, you will not find the entry anymore as the map will look in the wrong bucket for the entry.
In the case of ThreadLocal this would not be a problem, as it does not override equals() and hashCode() and thus the hashCode() will not change if you change the object, so you could safely use the ThreadLocal as key.
As Jaroslaw Pawlak commented, since ThreadLocal doesn't implement hashCode() and equals() it is not suitable for the key in HashMap, at least if you expect it to be well behaved.
Even if it did, it would be useless. Considering the use-case of ThreadLocal, it would be far clearer to use the contained object as the key.
Having a map with one ThreadLocal (with thread specific contents) mapping just ends up with having the internal map of ThreadLocal (the one that maps the thread to the value) being used for the actual mappings.
Not to mention that ThreadLocal instances are somewhat recommended against. The common use cases they have are solved by introducing "native" threadlocal classes, such as java.util.concurrent.ThreadSafeRandom.

Reason HashMap does not implement Iterable interface? [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 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.

LinkedHashMap order [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 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.

Categories

Resources