Higher and higher

Web Push?
IDL Design
Java In Practice
Contact Us
-- Home --


A new look for a New Year! Help us to reach new summits.

Selected Partners

Tricks for Collections

No Generic Types

By Benoit Xhenseval.

I'm crying for generic types, yes templates... it will happen for Java... one day!
In the meantime, we are using the collections (Vector, Hashtable, etc or better List, Map, Set etc)
You will know that:

  • Vector and Hashtable are synchronized by default and are therefore safe... and slower!
  • I prefer using the interface List and Map and the implementations HashMap and ArrayList. But there are other too SortedSet, TreeSet etc

Using collections

Any Java developer will know that:

  1. we do an awful lot of casting as those classes store only "Object"s and not primitive types
  2. we do create a lot of Objects, especially if you want to update a number kept in a collection.
Example: Say you want to keep a Map of String-Integer and you will change the value of the integer on a regular basis...

Let's leave point 1/ for now and see what we can do on point 2/, the memory! Quick solution is:
	map.put("Hello", new Integer(1));
to modify it:
	Integer i = (Integer)map.get("Hello");
	map.put("Hello",new Integer(1+ i.intValue()));
yuk yuk yuk!

The nice trick that will save a lot of memory is to use arrays of primitive types!
	int[] i = new int[1];
	map.put("Hello", i);
to modify it:
	int[] i = (int[])map.get("Hello");
Better isn't it?
Well, enjoy!

© 2003 Xhenseval.com. All rights reserved. Page design by B a s i c T e m p l a t e s . c o m.
Site Meter