Reputation:
I was converting some code from java to C#, I encountered ArrayList<Integer> values = hashtable.get(h);
. Question aroused Does Hashtable get method returns more than one value?
Upvotes: 0
Views: 566
Reputation: 2896
It does only return a list of values if you put that list in the map (under the certain key).
Map<String, List<Object>> map = new HashMap<>();
... // init map
List<Object> list = map.get(KEY);
but
Map<String, Object> map = new HashMap<>();
map.put(KEY, obj1);
map.put(KEY, obj2);
Object obj = map.get(KEY);
Upvotes: 0
Reputation: 938
If you wold like to have many values for one key use Guava
=> Multimap
Documentation:
http://guava-libraries.googlecode.com/svn-history/r13/trunk/javadoc/com/google/common/collect/Multimap.html
Upvotes: 0
Reputation: 122018
The return type of get() method
is Object
. So it is a single Object
. But the type can be a List
or Any Class
in Java.
So the returning Object
purely depends on What you inserted before.
Upvotes: 0
Reputation: 1850
An ArrayList is one value (an arraylist) by itself
HashTable<something, ArrayList<Integer>> hashtable = new HashTable<something, ArrayList<Integer>>();
So it's gonna map the "something" to an arraylist of integers (i.e. a list)
Upvotes: 0
Reputation: 27346
A HashTable
returns one value. If that value happens to be an object of type Collection
, then that one value will point to several other values.
For example
HashTable<String, ArrayList<Integer>> table = new HashTable<String, ArrayList<Integer>>();
// Populate it with values.
ArrayList<Integer> value = table.get("KEY");
How is this possible?
Simple. Java Generics. This is where you declare a Generic type
in a class, and you define it's type at run time. For example:
public class Test<T>
{
private T instance;
public Test(T instance)
{
this.instance = instance;
}
}
That means you can declare this class any way you want.
Test<String> test = new Test<String>();
Test<Integer> test2 = new Test<Integer>();
And the type of instance
will be whatever you declare it as.
And because T
defaults to type Object
, you can even put a Collection
in there.
Test<ArrayList<String>> test3 = new Test<ArrayList<String>>();
Upvotes: 1