Collection

G

Garg

Hi,

in ArrayList, Vector we can get the value by providing posting number
Like:

String str = (String) arrList.get(4);

but arrayList can only store one object.

HashMap, TreeMap can store two maps (key and Object).

Can i get the value of the key and Object stored at the 4th place.

is there any way to achieve this.

Thanks
Tarun Garg
 
M

Matt Humphrey

| Hi,
|
| in ArrayList, Vector we can get the value by providing posting number
| Like:
|
| String str = (String) arrList.get(4);
|
| but arrayList can only store one object.
|
| HashMap, TreeMap can store two maps (key and Object).
|
| Can i get the value of the key and Object stored at the 4th place.
|
| is there any way to achieve this.

You can get a list of the key-value pairs in the hash map and then pick off
the one you want by saying:

List <Map.Entry<K,V>> entryList = new ArrayList <Map.Entry<K,V>>
(myHashMap.entrySet());
K key = entryList.get(4).getKey();
V value = entryList.get(4).getValue();

and get a list of the key-value pairs in the hash map and then pick off the
one you want. However, because the order of the items in the list depends
on their hashcodes and the order they were inserted, you can't easily tell
what the 4th item mean--it could be anything. If you really just want to
iterate over them, use:

for (Map.Entry <K,V> e : entryList.entrySet()) {
}

A LinkedHashMap preserves the order in which items are entered so indexed
retrieval is more meaningful, although you still have to convert to a List
to get the item you want. A TreeMap has a natural order, but you still have
to convert it to a List as you do above. The values will be in the order of
the keys.

Matt Humphrey http://www.iviz.com/
 
L

Lew

Garg said:
| in ArrayList, Vector we can get the value by providing posting number

In any List.
| Like:
|
| String str = (String) arrList.get(4);

This cast should not be necessary. Also, "arrList" is not a good name for a
variable.
| but arrayList can only store one object.

You mean "only one object per slot", but that's no problem because that object
can hold any number of references.
| HashMap, TreeMap can store two maps (key and Object).

No, they cannot store two "maps", they store two objects in each slot, a key
and a value, and the value type need not be Object.
| Can i [sic] get the value of the key and Object stored at the 4th place.
|
| is there any way to achieve this.

Map doesn't just store a pair, it stores a pair /indexed by the key/. It
sounds like this is more than you need.

Declare a class to hold the pair of values, say, Pair <T, U>, and put
instances of that class in your list. That's how you'd do it with a Map,
where the "pair" class is Map.Entry, only with the custom solution you
dispense with the unnecessary machinery.

As Matt Humphrey pointed out, unless you specify a particular Map
implementation you lose any guarantee of order. If you do specify a
particular Map implementation, you are mandating machinery that you do not
actually need.

List< Pair <T, U>> is the way to go.
 
G

Garg

Thanks for your suggestions.

I tried to implement
List <Map.Entry<K,V>> entryList = new ArrayList <Map.Entry<K,V>>
(myHashMap.entrySet());
K key = entryList.get(4).getKey();
V value = entryList.get(4).getValue();

But i am couldn't be able to compile this.

so I implement this

HashMap hm1 = new HashMap();

Set ks = hm1.keySet();

Object[] arrks = ks.toArray();

for (int i = 0; i < arrks.length; i++)
{
String key = arrks.toString();
System.out.println("result i "+i+", key "+key+", object
"+hm1.get(key));
}


but as Matt mentioned that the order deppends on the hashcode and
order they are inserted(i think it only depends on the hashcode).

garg
 
L

Lew

Garg said:
but as Matt mentioned that the order deppends on the hashcode and
order they are inserted(i [sic] think it only depends on the hashcode).

Sort of, and it can change over the life of the Map.
I tried to implement
List <Map.Entry<K,V>> entryList = new ArrayList <Map.Entry<K,V>>

You do not need to mix Map and List in this way.

You should not embed the implementing type ("List") in the variable name. A
name that documents the /logical/ purpose is superior, and will not need
change as much if you refactor. Consider a name like "entries" for this one.
(myHashMap.entrySet());

Why make a list when you can iterate right over the Set? It's a lot of extra
copying and complexity for no gain.
K key = entryList.get(4).getKey();
V value = entryList.get(4).getValue();

But i [sic] am couldn't be able to compile this.

Would you be willing to show us an SSCCE
<http://www.physci.org/codes/sscce.html>
and copy-and-paste the error messages for us?

Comments based on the lack of information so far:

- You left out the generic types K and V in the declaration of your class that
has the "entryList" member. Thus K and V were not recognized types in the
compilation.

- You should declare your own wrapper type to hold the pair of values you want
to store, unless you truly want them to have a key-value relationship. The
purpose of a Map is to hold associations; using a Map as a List is overkill.
Instead, use a List from the get-go, and skip using a Map altogether.

- If, OTOH, you do need the associative lookup and only occasionally need to
loop through the entrySet, then just iterate over the entrySet. For most
implementations of Map, the order is irrelevant and will change between calls.

- The use of a Map to hold an association between keys and values is at
variance with the notion of ordering a list of value pairs by some intrinsic
order. For the latter, use a sorted
List <T extends Comparable<? super T>>
or List<T> sorted using a
Comparator<? super T>
or a SortedSet<T>. For the former where sort order really does matter, use a
SortedMap<T>. Matt Humphrey called your attention to the TreeMap
implementation. You should be able to simply iterate over that.

<http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)>

<http://java.sun.com/javase/6/docs/a...ml#sort(java.util.List, java.util.Comparator)>

<http://java.sun.com/javase/6/docs/api/java/util/SortedSet.html>
<http://java.sun.com/javase/6/docs/api/java/util/SortedMap.html>

- It is unlikely that you actually need both Mapness and sortedness.
 
R

Roedy Green

Can i get the value of the key and Object stored at the 4th place.

No. Keys are not stored that simply inside. see
http://mindprod.com/jgloss/hashtable.html to understand the structure.


What you can do is create a ArrayList of the objects. Perhaps you can
extract the key from the Object. If not create a class with both key
and object and pout those in the ArrayList or have two ArrayLists one
for keys and one for objects.
 
L

Lasse Reichstein Nielsen

Garg said:
in ArrayList, Vector we can get the value by providing posting number
Like:

String str = (String) arrList.get(4);

but arrayList can only store one object.

HashMap, TreeMap can store two maps (key and Object).

Can i get the value of the key and Object stored at the 4th place.

What fourth place? A HashMap has no inherent order, so you can't even
talk about places.

A LinkedHashMap guarantees the order of iteration to be preserved by
additions. In that case you can talk about the fourth element.
You'd get that by:
Iterator iter = myLinkedMap.entrySet().iterator();
iter.next();
iter.next();
iter.next();
Map.Entry fourth = iter.next();

However, if you want a list of pairs, don't misuse a map for it.
Make a list of pairs!

public class Pair<S,T> {
private final S fst;
private final T snd;
public Pair(S fst, T snd) {
this.fst = fst;
this.snd = snd;
}
public S getFirst() {
return fst;
}
public T getSecond() {
return snd;
}
}

private List<Pair<String,String>> list = new ArrayList<Pair<String,String>>;
// ...
Pair<String,String> fourth = list.get(4);


/L
 
M

Matt Humphrey

| Thanks for your suggestions.
|


|
| but as Matt mentioned that the order deppends on the hashcode and
| order they are inserted(i think it only depends on the hashcode).

Just to clarify why the order of insertion matters, two distinct keys
("AAA", "QQQ") may produce the same hashcode and end up in the same bucket
list. In some cases you'll get AAA and then QQQ and in other cases you'll
get QQQ and then AAA, depending on how they were added to the list.
 
L

Lew

Matt said:
| Thanks for your suggestions.
|


|
| but as Matt mentioned that the order deppends on the hashcode and
| order they are inserted(i think it only depends on the hashcode).

Just to clarify why the order of insertion matters, two distinct keys
("AAA", "QQQ") may produce the same hashcode and end up in the same bucket
list. In some cases you'll get AAA and then QQQ and in other cases you'll
get QQQ and then AAA, depending on how they were added to the list.

That's not all. For HashMap and other implementations, the order can change
during the life of the Map. When the Map grows to accommodate more entries,
it rearranges where things are in the structure.

This class makes no guarantees as to the order of the map;
in particular, it does not guarantee that the order will remain constant over time. ....
When the number of entries in the hash table exceeds
the product of the load factor and the current capacity,
the hash table is /rehashed/
(that is, internal data structures are rebuilt)
so that the hash table has approximately twice the number of buckets.
(emph. orig.)
 
D

Daniel Pitts

Matt said:
| Thanks for your suggestions.
|


|
| but as Matt mentioned that the order deppends on the hashcode and
| order they are inserted(i think it only depends on the hashcode).

Just to clarify why the order of insertion matters, two distinct keys
("AAA", "QQQ") may produce the same hashcode and end up in the same bucket
list. In some cases you'll get AAA and then QQQ and in other cases you'll
get QQQ and then AAA, depending on how they were added to the list.
Also, if the hash table gets resized, they may end up in different
buckets in a different order!

LinkedHashSet will let you iterate in insertion order.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

hash map / collection choice 14
Tasks 1
School Project 1
which collection to use 14
SENTINEL CONTROL LOOP WHEN DEALING WITH TWO ARRAYS 1
Class Struktur 3
Copying into ArrayList 2
create collection of collection 1

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top