Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

Collection

Thread view: 
Garg - 29 Oct 2007 11:36 GMT
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
Matt Humphrey - 29 Oct 2007 12:19 GMT
| Hi,
|
[quoted text clipped - 10 lines]
|
| 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/
Lew - 29 Oct 2007 15:13 GMT
"Garg" <sendtogarg@gmail.com> wrote:
> | 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.

Signature

Lew

Garg - 29 Oct 2007 16:21 GMT
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[i].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
Lew - 29 Oct 2007 17:04 GMT
> 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/api/java/util/Collections.html#sort(java.util.
List,%20java.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.

Signature

Lew

Matt Humphrey - 30 Oct 2007 20:11 GMT
| 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.
Lew - 31 Oct 2007 01:42 GMT
> | Thanks for your suggestions.
>
[quoted text clipped - 5 lines]
> 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.

<http://java.sun.com/javase/6/docs/api/java/util/HashMap.html>
> 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.)

Signature

Lew

Daniel Pitts - 31 Oct 2007 02:22 GMT
> | Thanks for your suggestions.
>
[quoted text clipped - 5 lines]
> 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.

Signature

Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Roedy Green - 29 Oct 2007 17:12 GMT
>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.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lasse Reichstein Nielsen - 29 Oct 2007 20:02 GMT
> in ArrayList, Vector we can get the value by providing posting number
> Like:
[quoted text clipped - 6 lines]
>
> 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
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.