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

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.

Which is faster in accessing elements from Java collections [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to understand which is faster in accessing elements from collections in Java like ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap etc.
From this question: Suitable java collection for fast get and fast removal, I got to know that ArrayList takes O(1) and TreeMap as O(log n)
where as this: Map/ArrayList: which one is faster to search for an element shows that ArryList is O(n), HashMap as O(1) and TreeMap as O(log n)
where as this: Why is it faster to process a sorted array than an unsorted array? says that sorted array is faster than unsorted array. As the elements in TreeMap are sorted then can I assume all sorted collections are faster than un-sorted collections?
Please help me in understanding which is faster to use in accessing elements from java collections of list, set, map etc implementations.
Every collection type is suitable for a particular scenario. There is no fastest or best collection.
If you need fast access to elements using index, ArrayList is your answer.
If you need fast access to elements using a key, use HashMap.
If you need fast add and removal of elements, use LinkedList (but it has a very poor index access performance).
and so on.
It depends whether you want to access an element as index based(in case of list) or see if an Object exists in the Collection
If you want to access an element index based,then arraylist is faster as it implements RandomAccess Marker interface and is internally backed by an array.
Sets are internally backed by Map ,so performance of Map and Set is same(Set use a dummy Object as value in key-value pair).I would suggest you to use a HashSet.
The problem that many programmers dont notice is that performance of Hashset or HashMap is best O(1) when the hashing function of Key Object is good,ie. it produces different values for different Objects (though this is not a strict requirement).
NOTE :- If you are Hashing funciton is not good,it degrades to a LinkedList internally and its performance degrades to O(n)
My personal preference is to Use EnumMap or EnumSet.It simply uses the Enum values for its functioning and programmers dont have to worry about the Enum's hashcode/equals function.For rest other cases,use HashSet or HashMap(if you dont have to make it ordered)

Method naming in Map class: keySet(), entrySet() and values() [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
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.

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