93
Collections FAQ From jGuru Generated Sep 13, 2005 12:49:37 PM Location: http://www.jguru.com/faq/Collections Ownership: http://www.jguru.com/misc/user-agree.jsp#ownership . Why is the Dictionary class not an interface? Location: http://www.jguru.com/faq/view.jsp?EID=963 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Rumor has it that the Dictionary class is so old that the concept of interfaces didn't exist yet. Once interfaces were introduced, nobody bothered to change Dictionary to an interface. What other frameworks are there for general data structures? Location: http://www.jguru.com/faq/view.jsp?EID=965 Created: Nov 14, 1999 Modified: 2000-07-25 21:34:44.324 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) The Generic Collection Library for Java - JGL from ObjectSpace has been around since 1996 and the same version works with both JDK 1.1 and the Java 2 SDK. Doug Lea's Collections Package is a precursor to the current Collections Framework. If you are looking for template support, the Generic Java Language Extension includes a retrofitted version of the Collections Framework with template support. A new entry into the mix is Colt which is meant for scientific computing, and includes data structures for numerical operations. Comments and alternative answers Trove4j, pcj, tclib... Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Mar 10, 2003 Trove4j (aka GNU Trove): http://trove4j.sourceforge.net/ http://pcj.sourceforge.net/ http://www.sosnoski.com/opensrc/tclib/ Where can I find an article comparing JGL and the Collections Framework? Location: http://www.jguru.com/faq/view.jsp?EID=966 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Collections FAQ From jGuru

Embed Size (px)

Citation preview

Page 1: Collections FAQ From jGuru

Collections FAQ From jGuru Generated Sep 13, 2005 12:49:37 PM

Location: http://www.jguru.com/faq/CollectionsOwnership: http://www.jguru.com/misc/user-agree.jsp#ownership.

Why is the Dictionary class not an interface?Location: http://www.jguru.com/faq/view.jsp?EID=963 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Rumor has it that the Dictionary class is so old that the concept of interfaces didn't exist yet. Once interfaces were introduced, nobody bothered to change Dictionary to an interface.

What other frameworks are there for general data structures?Location: http://www.jguru.com/faq/view.jsp?EID=965 Created: Nov 14, 1999 Modified: 2000-07-25 21:34:44.324Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Generic Collection Library for Java - JGL from ObjectSpace has been around since 1996 and the same version works with both JDK 1.1 and the Java 2 SDK. Doug Lea's Collections Package is a precursor to the current Collections Framework. If you are looking for template support, the Generic Java Language Extension includes a retrofitted version of the Collections Framework with template support. A new entry into the mix is Colt which is meant for scientific computing, and includes data structures for numerical operations.Comments and alternative answers

Trove4j, pcj, tclib... Author: Sean Sullivan (http://www.jguru.com/guru/viewbio.jsp?EID=203382), Mar 10, 2003 Trove4j (aka GNU Trove): http://trove4j.sourceforge.net/ http://pcj.sourceforge.net/ http://www.sosnoski.com/opensrc/tclib/

Where can I find an article comparing JGL and the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=966 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

JavaWorld posted an article comparing the two frameworks back in their January 1999 issue: The battle of the container frameworks: which should you use?

Where can I learn how to use the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=967 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Page 2: Collections FAQ From jGuru

The Java Developer Connection has a short course available at http://developer.java.sun.com/developer/onlineTraining/collections/. In addition, the online Java Tutorial book has a trail dedicated to the Collections Framework available: http://java.sun.com/docs/books/tutorial/collections/.

Where do I get the Collections Framework for use with JDK 1.1?Location: http://www.jguru.com/faq/view.jsp?EID=969 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The subset of the Collections Framework for use with JDK 1.1 is available with the InfoBus information: http://java.sun.com/beans/infobus/index.html#DOWNLOAD_COLLECTIONS.

What do I have to know about the Collections Framework to be a Certified Java Programmer?Location: http://www.jguru.com/faq/view.jsp?EID=970 Created: Nov 14, 1999 Modified: 2000-07-05 20:37:08.666Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

According to the exam objectives, you need to: "Make appropriate selection of collection classes/interfaces to suit specified behavior requirements." Comments and alternative answers

Helpfull.... Author: Ola Tartakovsky (http://www.jguru.com/guru/viewbio.jsp?EID=863596), May 2, 2002-

How do I use an Iterator to go through a Collection?Location: http://www.jguru.com/faq/view.jsp?EID=971 Created: Nov 14, 1999 Modified: 2005-09-12 14:08:53.744Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Collection collection = ...;Iterator iterator = collection.iterator();while (iterator.hasNext()) { Object element = iterator.next(); // Do something with element }}

How do I use a ListIterator to go through a List backwards?Location: http://www.jguru.com/faq/view.jsp?EID=972 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

List list = ...;ListIterator iterator = list.listIterator(list.size());while (iterator.hasPrevious()) { Object element = iterator.previous(); // Process element

Page 3: Collections FAQ From jGuru

}

How do I count the frequency of some word/object?Location: http://www.jguru.com/faq/view.jsp?EID=973 Created: Nov 14, 1999 Modified: 1999-11-17 06:53:58.057Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Map interface can be used to count the number of times a word/object appears. The following program demonstrates counting word frequency from the command line:

import java.util.*;

public class MapExample { public static void main(String args[]) { Map map = new HashMap(); Integer ONE = new Integer(1); for (int i=0, n=args.length; i<n; i++) { String key = args[i]; Integer frequency = (Integer)map.get(key); if (frequency == null) { frequency = ONE; } else { int value = frequency.intValue(); frequency = new Integer(value + 1); } map.put(key, frequency); } System.out.println(map); Map sortedMap = new TreeMap(map); System.out.println(sortedMap); }}

How do I properly alphabetize (sort) a list of strings in a language-sensitive manner?Location: http://www.jguru.com/faq/view.jsp?EID=974 Created: Nov 14, 1999 Modified: 2000-01-15 15:41:30.423Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This is actually outside the scope of the Collections Framework. Instead, it is part of the java.text package with the Collator and CollationKey classes.

The following example demonstrates this capability:

import java.text.*;import java.util.*;

public class CollatorTest { public static void main(String args[]) { Collator collator = Collator.getInstance(); CollationKey key1 = collator.getCollationKey("Tom"); CollationKey key2 =

Page 4: Collections FAQ From jGuru

collator.getCollationKey("tom"); CollationKey key3 = collator.getCollationKey("thom"); CollationKey key4 = collator.getCollationKey("Thom"); CollationKey key5 = collator.getCollationKey("Thomas");

Set set = new TreeSet(); set.add(key1); set.add(key2); set.add(key3); set.add(key4); set.add(key5); printCollection(set); } static private void printCollection( Collection collection) { boolean first = true; Iterator iterator = collection.iterator(); System.out.print("["); while (iterator.hasNext()) { if (first) { first = false; } else { System.out.print(", "); } CollationKey key = (CollationKey)iterator.next(); System.out.print(key.getSourceString()); } System.out.println("]"); }}Comments and alternative answers

can i pass a collection to a collator class Author: ashwini iyer (http://www.jguru.com/guru/viewbio.jsp?EID=1084160), May 12, 2003this code was really very helpful to me too i have the same problem how do u pass collection tocollator it has 300 entries what will happen will there be performance problems? will it slow down?thanks a lot for the collator code!IF I GET the collcetion to collator thing i would be gratefull!

can i pass a collection to a collator class Author: ashwini iyer (http://www.jguru.com/guru/viewbio.jsp?EID=1084160), May 12, 2003this code was really very helpful to me too

Page 5: Collections FAQ From jGuru

i have the same problem how do u pass collection tocollator it has 300 entries what will happen will there be performance problems? will it slow down?thanks a lot for the collator code!IF I GET the collcetion to collator thing i would be gratefull!

can i pass a collection to a collator class Author: ashwini iyer (http://www.jguru.com/guru/viewbio.jsp?EID=1084160), May 12, 2003this code was really very helpful to me too i have the same problem how do u pass collection tocollator it has 300 entries what will happen will there be performance problems? will it slow down?thanks a lot for the collator code!IF I GET the collcetion to collator thing i would be gratefull!

Sorting List Running Example Author: Parag Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=1136228), Dec 30, 2003import java.util.*; class Sort { private Vector list = new Vector(); public Sort() { list.addElement(new String("parag")); list.addElement(new String("amit")); list.addElement(new String("priyank")); } public void sort() { Collections.sort(list); } public void print() { System.out.println(list); } public static void main(String [] args) { Sort s = new Sort(); s.sort(); s.print(); } }

Sorting List Running Example Author: Parag Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=1136228), Dec 30, 2003

import java.util.*;

class Sort {

private Vector list = new Vector();

public Sort() {

Page 6: Collections FAQ From jGuru

list.addElement(new String("parag"));

list.addElement(new String("amit"));

list.addElement(new String("priyank"));

}

public void sort() {

Collections.sort(list);

}

public void print() {

System.out.println(list);

}

public static void main(String [] args) {

Sort s = new Sort();

s.sort();

s.print();

}

}

Sorting List Running Example Author: Parag Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=1136228), Dec 30, 2003

Page 7: Collections FAQ From jGuru

import java.util.*;

class Sort {

private Vector list = new Vector();

public Sort() {

list.addElement(new String("parag"));

list.addElement(new String("amit"));

list.addElement(new String("priyank"));

}

public void sort() {

Collections.sort(list);

}

public void print() {

System.out.println(list);

}

public static void main(String [] args) {

Sort s = new Sort();

s.sort();

s.print();

}

Page 8: Collections FAQ From jGuru

}

How do I do a case-insensitive string sort in a language-insensitive manner?Location: http://www.jguru.com/faq/view.jsp?EID=976 Created: Nov 14, 1999 Modified: 2001-07-24 08:17:45.982Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You need to use a new Comparator, not the default Comparable. The String class comes with a special Comparator you can use: String.CASE_INSENSITIVE_ORDER.

How do I sort objects into their reverse natural ordering?Location: http://www.jguru.com/faq/view.jsp?EID=977 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Collections.reverseOrder() method returns a Comparator that sorts objects that implement the Comparable interface in reverse order.

How do I use Enumeration to iterate through a collection?Location: http://www.jguru.com/faq/view.jsp?EID=978 Created: Nov 14, 1999 Modified: 2000-04-26 15:52:13.699Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Enumeration enum = ...;while (enum.hasMoreElements()) { Object element = iterator.nextElement(); // process element}

What newsgroups/mailing lists are available to ask questions about the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=980 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The comp.lang.java.programmer newsgroup is probably your best bet for Collections Framework questions. There is mailing list specific to ObjectSpace JGL-questions that you can subscribe to at http://www.objectspace.com/products/jglDiscGroups.htm.

The TreeMap documentation states that it is a red-black tree based implementation of the SortedMap interface. What are red-black trees?Location: http://www.jguru.com/faq/view.jsp?EID=981 Created: Nov 14, 1999 Modified: 2001-07-24 09:10:37.393Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

A red-black tree is a binary search tree where every node has two children or is a leaf. It ensures O(log N) search times, at a cost of a more complicated insertion (and deletion) process. In a red-black tree, every node is colored either red or black, with a

Page 9: Collections FAQ From jGuru

black root node, though a black root node isn't a requirement. In addition, if a node is red, its children must be black and every path from root to leaf (or null child node) must contain the same number of black nodes. These rather obscure rules ensure the tree is balanced.

How do I make an array larger?Location: http://www.jguru.com/faq/view.jsp?EID=982 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You cannot directly make an array larger. You must make a new (larger) array and copy the original elements into it, usually with System.arraycopy(). If you find yourself frequently doing this, the Vector class does this automatically for you, as long as your arrays are not of primitive data types.

How do you store a primitive data type within a Vector or other collections class?Location: http://www.jguru.com/faq/view.jsp?EID=983 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You need to wrap the primitive data type into one of the wrapper classes found in the java.lang package, like Integer, Float, or Double, as in:

Integer in = new Integer(5);

How do I create linked lists if there are no pointers?Location: http://www.jguru.com/faq/view.jsp?EID=984 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

No pointers does not mean no reference variables. You just can't deference them as you can in C/C++ or perform pointer arithmetic. You can still use abstract data types that require dynamic data structures. See the LinkedList class for an example of a linked list implementation.

How do I use an array with the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=985 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Arrays.asList() method provides a fixed-length List view of an array, where changes to the List are stored in the original array. The Arrays class also provides additional support methods for sorting and searching an array.

Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access?Location: http://www.jguru.com/faq/view.jsp?EID=986 Created: Nov 14, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access.

Page 10: Collections FAQ From jGuru

Where can I get the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=1007 Created: Nov 14, 1999 Modified: 2001-11-29 22:34:18.481Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Collections Framework is a core part of the Java 2 platform. You don't have to download anything more than the Java 2 SDK. For more information about the framework, the main documentation is available at http://www.javasoft.com/products/jdk/1.2/docs/guide/collections/.

There also is a subset of the Collections Framework available for JDK 1.1, see http://java.sun.com/beans/infobus/#collections.

Where can I find information about the design decisions made during the development of the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=1179 Created: Nov 20, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Sun provides a Design FAQ at http://java.sun.com/products/jdk/1.2/docs/guide/collections/designfaq.html that answers many questions concerning the design of the framework.

Which is the preferred collection class to use for storing database result sets?Location: http://www.jguru.com/faq/view.jsp?EID=2286 Created: Dec 9, 1999 Modified: 2000-07-30 09:48:38.772Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include:

Retains the original retrieval order Has quick insertion at the head/tail Doesn't have an internal size limitation like a Vector where when the size is

exceeded a new internal structure is created (or you have to find out size beforehand to size properly)

Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized

Basically:

ResultSet result = stmt.executeQuery("...");List list = new LinkedList();while(result.next()) { list.add(result.getString("col")); } If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

Page 11: Collections FAQ From jGuru

Why doesn't the Iterator interface extend the Enumeration interface?Location: http://www.jguru.com/faq/view.jsp?EID=2360 Created: Dec 10, 1999 Modified: 1999-12-10 23:38:24.46Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

If the Iterator interface extended the Enumeration interface, the Iterator interface would end up with five methods where two methods just called other methods in the interface. The designers of the framework wanted to get rid of the cumbersome Enumeration method names so had the Iterator interface stand on its own with new shorter method names.

How do I print a Collection?Location: http://www.jguru.com/faq/view.jsp?EID=2363 Created: Dec 10, 1999 Modified: 1999-12-10 23:45:18.768Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Collection Framework implementation classes override the toString() method to print out all the elements of the collection. If you create your own custom implementation, as long as your class is a subclass of AbstractMap or AbstractCollection you'll inherit this behavior. (Keep in mind that AbstractList and AbstractSet subclass AbstractCollection.)Comments and alternative answers

How do I print a Collection? Author: Andrew Ferguson (http://www.jguru.com/guru/viewbio.jsp?EID=1022145), Apr 16, 2003i keep having to write this bit of code to get a readable format tho..

public static void print(Collection c) {   for(Iterator i = c.iterator(); i.hasNext(); )      System.out.println(i.next());}

How do I print a Collection? Author: Andrew Ferguson (http://www.jguru.com/guru/viewbio.jsp?EID=1022145), Apr 16, 2003i keep having to write this bit of code to get a readable format tho..

public static void print(Collection c) {   for(Iterator i = c.iterator(); i.hasNext(); )      System.out.println(i.next());}

How do I synchronize a collection?Location: http://www.jguru.com/faq/view.jsp?EID=2816 Created: Dec 18, 1999 Modified: 1999-12-18 07:04:43.308Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Page 12: Collections FAQ From jGuru

With the Collections Framework, the new implementations are all unsynchronized by default. If you need synchronized access, you must synchronize things yourself. The Collections class offers a wrapper method for each of the six core collection interfaces that add synchronization to an arbitrary collections implementation. To ensure thread-safety, direct access to the original backing collection must be avoided.

For example, the following will synchronize an arbitrary List and lose the original reference so you can't access it directly:

List list = ...;list = Collections.synchronizedList(list);Comments and alternative answers

Re: How do I synchronize a collection? Author: Kalpeshkumar Soni (http://www.jguru.com/guru/viewbio.jsp?EID=916018), Jun 2, 2003It is imperative that the user manually synchronize on the returned collection when iterating over it:

Collection c = Collections.synchronizedCollection(myCollection); ... synchronized(c) { Iterator i = c.iterator(); // Must be in the synchronized block while (i.hasNext()) foo(i.next()); }

Failure to follow this advice may result in non-deterministic behavior

How do I do a case-sensitive sort in a language-insensitive manner? Location: http://www.jguru.com/faq/view.jsp?EID=3029 Created: Dec 20, 1999 Modified: 1999-12-20 22:52:31.793Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

If you have an array of primitives or an array of equivalent objects that implement the Comparable interface, all you need to do is call the sort() method of the java.util.Arrays class. If the class doesn't implement Comparable, you need to provide your own Comparator implementation to the sort() method.

How do I get the length of an array?Location: http://www.jguru.com/faq/view.jsp?EID=3035 Created: Dec 20, 1999 Modified: 1999-12-20 23:02:52.918Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

To avoid getting an ArrayIndexOutOfBoundsException, you can check for the array length from either the length instance variable or using reflection and calling java.lang.reflect.Array.getLength(), passing the array as an argument to the method. int length = args.length;// orint length2 = Array.getLength(args);

Page 13: Collections FAQ From jGuru

Comments and alternative answers

Note that Array.getLength(args) is only needed when... Author: Doug Bell (http://www.jguru.com/guru/viewbio.jsp?EID=113602), Aug 1, 2000Note that Array.getLength(args) is only needed when args is a generic Object reference and args.getClass().isArray() is true. If args is a reference to an array type, use args.length.

How can I speed up array accesses and turn off array bounds checking?Location: http://www.jguru.com/faq/view.jsp?EID=3038 Created: Dec 20, 1999 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You cannot. It is part of the security architecture of the Java runtime to ensure never accessing invalid memory space.Comments and alternative answers

Don't forget that dynamic compilation can sense when... Author: Terence Parr (http://www.jguru.com/guru/viewbio.jsp?EID=1), Dec 22, 1999Don't forget that dynamic compilation can sense when an array reference is in a loop whose index is bounded within the array size. In this case, the bounds check is superfluous and can be removed.

The null-pointer check can also be moved out of the loop via "loop-invariant code motion" stuff.

Does any of this really happen? Haven't checked, but I hope so. ;) In principle, dynamic compilers can do much more of this than a JIT or other a priori compiler.

Turning off Array Bounds Checking Author: Richard Bremner (http://www.jguru.com/guru/viewbio.jsp?EID=976227), Aug 5, 2002

I'm not sure if it still applies in the current family of jre's, but apparently you used to be able to turn off the Array Bound checking by encapsulating your array access in a try/catch;

try {

for (int i = 0; ; i++) {

myArray[i] = i;

}

Page 14: Collections FAQ From jGuru

catch (ArrayIndexOutOfBoundsException aioobe) {

//to be expected }

Even if this did work, I expect it would only be faster for very large arrays, richard

Re: Turning off Array Bounds Checking Author: Bernd Eckenfels (http://www.jguru.com/guru/viewbio.jsp?EID=1194484), Aug 20, 2004If you do it this way you _force_ the JIT engine to do bounds checking. Because the bounds checks are needed for the engine to raise the excaption.

See http://c2.com/cgi/wiki?CatchDontCheck

GreetingsBernd

How do I get the list of system properties that tell me things like which version of Java a user is running and their platform-specific line separator?Location: http://www.jguru.com/faq/view.jsp?EID=3825 Created: Dec 31, 1999 Modified: 2000-02-21 09:27:19.682Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The System.getProperties() method will return the standard property set. However, in untrusted applets, you can only ask for specific properties, as in System.getProperty("java.version").

How do I sort an array?Location: http://www.jguru.com/faq/view.jsp?EID=11025 Created: Feb 3, 2000 Modified: 2000-02-03 00:24:17.523Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Arrays class in java.util provides a series of sort() methods for sorting arrays. If the array is an array of primitives or an array of a class that implements Comparable then you can just call the method directly:

Arrays.sort(theArray);

If, however, it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.

Arrays.sort(theArray, theComparator);

Page 15: Collections FAQ From jGuru

How can I implement a List (ordered collection) that keeps an index (i.e. a Map) of its contents?Location: http://www.jguru.com/faq/view.jsp?EID=11808 Created: Feb 6, 2000 Modified: 2001-07-24 09:21:44.644Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

You can't. Each of the Map and List interfaces define a remove(Object o) method. Each method returns a different type (Map returns an Object while List returns a boolean). Because the compiler doesn't permit overloaded methods that differ by only return type, you cannot create a class that implements both the List and Map interface.

If you need a Map that maintains insertion order, see the LinkedHashMap added in Java 1.4.

Comments and alternative answers

I've got open-source code that solves this, in two... Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Mar 1, 2000I've got open-source code that solves this, in two different classes. My EntryList is a List that stores key-value pairs; it adds get(Object key) and put(Object key, Object value) and a few other methods to the standard ArrayList. My IndexedList is a normal List that builds an index of its contents based on a callback function you pass it - so, for example, if storing Person objects, you could provide a callback that calls getName() for the index.

Both of my Lists also have a toMap() method which returns a true java.util.Map object for you to play with.

Find them at http://www.purpletech.com/code/.

How can I save/load application settings that I would normally use .ini files or the Windows Registry? Location: http://www.jguru.com/faq/view.jsp?EID=20462 Created: Mar 5, 2000 Modified: 2005-09-12 14:42:49.101Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by chih-ming yan (http://www.jguru.com/guru/viewbio.jsp?EID=20234

You can use Java property files for storing settings for an application. Use the java.util.Properties class, which includes a load and store method.

You can also use a PropertyResourceBundle, but there is no way to automatically store these files built into the Java classes, only read them.

Page 16: Collections FAQ From jGuru

What collection works best for maintaining a family tree, where each node can have multiple parents and multiple children, spouse relationships, etc.?Location: http://www.jguru.com/faq/view.jsp?EID=26298 Created: Mar 20, 2000 Modified: 2000-03-20 17:42:30.647Author: Joseph Shelby (http://www.jguru.com/guru/viewbio.jsp?EID=26292) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

With Collections by themselves, there isn't one. What you're asking for is a Labeled Directed Graph (A directed graph where the graph edges have labels describing the relationship). A rather complex object.

You'd have to design that yourself (though you can use Collection objects like Lists in the implementation as a convenience), and design Comparators to support your final implementation classes of a "FamilyTreePerson" for sorting purposes (like sort by name or sort by birthdate, etc.).

After that, you have to decide what "Iteration" over the tree really means and define Iterator classes over the Graph. After that, completing the Collection interface should be pretty simple.

In other words, you've got a lot of design work to do, but designing it well can lead to a rather flexible framework (or at least a source of Patterns) for future use. In particular, keep in mind in building such a LabeledDirectedGraph beast on how you can keep "Family Tree" concepts out of it. The Label provider should be an Interface function object, like Comparator.

This is getting heavily into "Generic Programming", and I advise you read more about that (most GP work is being done in connection with the STL from C++).

Is there a way to create a homogenous collection in Java?How do I make a collection where all the elements within it are a specific data type? Location: http://www.jguru.com/faq/view.jsp?EID=26299 Created: Mar 20, 2000 Modified: 2001-07-24 09:44:14.784Author: Joseph Shelby (http://www.jguru.com/guru/viewbio.jsp?EID=26292) Question originally posed by Tim Rohaly PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=10

You can wait for Generics to be added to Java or...

You'd have to build one yourself. Basically, you're creating a class that is a Proxy (Gang Of Four design pattern) around the actual Collection.

This works similarly to the way the (hidden) Synchronized versions in Collections work. They contain a reference to the original collection object that does the "real" work, but restrict access to it by synchronizing all the access methods.

What you'd be doing in this case is restricting access by keeping a reference to the Class object of the class you want to restrict your collection to contain, and throw IllegalArgumentExceptions whenever there's an attempt to add an object not of that class.

Page 17: Collections FAQ From jGuru

There's no way to enforce compile-time type safety in this manner. The API using "Object" references can't be changed in Collection.

You can also wrap a collection by a Proxy that provides the alternative API that has type-safe method signatures. This is what's done by the StringTokenizer API (which implements Enumeration, and wraps Enumeration with String versions of the same methods).

Otherwise, create your own class with its own signatures, and keep the Collection strictly private. This is best done if you are designing a class for others to use.

What's the fastest way to traverse all the elements of a Vector?Location: http://www.jguru.com/faq/view.jsp?EID=33288 Created: Apr 6, 2000 Modified: 2001-11-29 22:40:29.604Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

If speed is of the essence, do not use a Vector. Instead, use an ArrayList. All accesses to a Vector are synchronized, whether you need it or not. If you know you aren’t accessing the structure from multiple threads, the ArrayList will be much faster.

With that said, what about if you need to stay with a Vector? There are at least four ways to traverse through all the elements of a Vector:

Using a for loop and accessing each element with elementAt(index) or get(index)

Using an Emumeration Using an Iterator Using an Enumeration/Iterator, but relying on an exception to catch ending

Of the four, there are neglible differences in performance. While looping through to a specific index is a little faster, you lose the flexibility of changing to another data structure at a later time. With the Enumeration / Iterator approach, there is the added cost to create the Enumeration/Iterator to walk through. With the exception approach, you are relying on NoSuchElementException to be thrown to catch the ending of the walk through. While creating the exception takes time, this approach avoids the repeated test of hasMoreElement(). As the structure gets larger, avoiding the test condition can save lots of time.

Added by Doug Bell:

You left out what is often the fastest means to sequence though the members of a Vector: get a copy of the elements in an array and sequence through the array. This results in either synchronized calls, after which there is not any method overhead at all:

Object[] elements = vector.toArray(); // JDK 1.2

or

Object[] elements;

Page 18: Collections FAQ From jGuru

synchronized (vector) { // needed if concurrently accessed elements = new Object[vector.size()]; vector.copyInto(elements); }

Further, if you know the types of the elements in the Vector, you can put the copy of the elements in an array of the known type and eliminate the casting overhead necessary to cast the Object references to the known type.

JDK 1.1:

MyType[] elements; synchronized (vector) { // needed if concurrently accessed elements = new MyType[vector.size()]; vector.copyInto(elements); }

JDK 1.2:

MyType[] elements = new MyType[vector.size()]; elements = (MyType[])vector.toArray(elements);

Note that while System.arraycopy() still needs to check the types of the objects when copying between arrays of different types, the check is performed much more efficiently than performing the cast operation on each element individually.

Getting an array of elements is faster than the other suggested approaches for vectors of more than a few elements. Although it does incur the overhead of instantiating a copy of the array and copying the elements, these operations generally take much less time than the repeated synchronization. As an added benefit (usually at least, depends on what you're trying to do) the process of iterating through the elements is predictable even in the presence of other threads which modify the vector. (You can also achieve this using any of the other techniques by placing the code that sequences the vector in a block synchronized on the Vector object.)

A fifth way actually exists that is faster for traversal, but requires additional setup and memory. Copy the elements out of the collection and into an array. You can even make the array the right data type.

How does a Hashtable internally maintain the key-value pairs?Location: http://www.jguru.com/faq/view.jsp?EID=43224 Created: May 2, 2000 Modified: 2000-05-02 05:15:12.121Author: Frank Steidinger (http://www.jguru.com/guru/viewbio.jsp?EID=34216) Question originally posed by Pramod Hirole (http://www.jguru.com/guru/viewbio.jsp?EID=41443

Page 19: Collections FAQ From jGuru

The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

How do I look through each element of a HashMap?Location: http://www.jguru.com/faq/view.jsp?EID=67916 Created: Jun 7, 2000 Modified: 2000-06-07 10:49:02.409Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Steffen Schlachter (http://www.jguru.com/guru/viewbio.jsp?EID=66154

To go through all the elements of a HashMap, or any class that implements the Map interface, call the entrySet() or keySet() methods than loop through what is returned. The entrySet() returns a group of Map.Entry elements, whereas the keySet() method just returns a Set of key elements. If you then want what the key refers to, you'd have to look them up.

Once you have a Set to work with, you would then use an Iterator to go through all its elements. The following demonstrates:

Map map = some hash mapSet set = map.keySet();Iterator it = set.iterator();while (it.hasNext()) { System.out.println(it.next());}

How do I create a read-only collection?Location: http://www.jguru.com/faq/view.jsp?EID=102250 Created: Jul 14, 2000 Modified: 2000-07-17 09:13:00.244Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Collections class has six methods to help out here: unmodifiableCollection(Collection c) unmodifiableList(List list) unmodifiableMap(Map m) unmodifiableSet(Set s) unmodifiableSortedMap(SortedMap m) unmodifiableSortedSet(SortedSet s)

If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException.

How can I process through the keys of a Hashtable in sorted order?Location: http://www.jguru.com/faq/view.jsp?EID=105643 Created: Jul 19, 2000 Modified: 2000-07-19 10:06:32.052Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by khyati patel (http://www.jguru.com/guru/viewbio.jsp?EID=105081

Page 20: Collections FAQ From jGuru

In order to get all the keys for a Hashtable, you use the keys() method to get an Enumeration or the keySet() method to get a Set. If you are using Java 2, and can use the collections framework, what you should do is get the key set of the Hashtable and create a TreeSet from it. You can then get an iterator() from the created TreeSet that will have the keys in order. If you can't use the collections framework, you'll have the sort the Enumeration you get back from keys() yourself.Comments and alternative answers

This does not answer the question. Author: chris gutteridge (http://www.jguru.com/guru/viewbio.jsp?EID=1027896), Nov 20, 2002You say how to get a set out of it, but don't say how to sort that set. so it's not that helpful.

Re: This does not answer the question. Author: Andrew Hart (http://www.jguru.com/guru/viewbio.jsp?EID=935096), Jan 15, 2003Yes, it does. A TreeSet is, by definition, sorted. So, when you construct a TreeSet passing the constructor a collection, it is sorted. If you would like it spelled out: Iterator it = new TreeSet (someHashtable.keySet()).iterator();

while (it.hasNext()) {

// Now, you're reading the key objects in

// the natural sort order...

YourKeyClass yourKey = (YourKeyClass) it.next();

// Refer to the original Hashtable for the

// corresponding value...

YourValue yourValue = (YourValue) someHashtable.get(yourKey);

}

So, not only does it answer the question, it does so in a very terse and elegant manner.

Re: This does not answer the question. Author: Andrew Hart (http://www.jguru.com/guru/viewbio.jsp?EID=935096), Jan 15, 2003Yes, it does. A TreeSet is, by definition, sorted. So, when you construct a TreeSet passing the constructor a collection, it is sorted. If you would like it spelled out: Iterator it = new TreeSet (someHashtable.keySet()).iterator();

Page 21: Collections FAQ From jGuru

while (it.hasNext()) {

// Now, you're reading the key objects in

// the natural sort order...

YourKeyClass yourKey = (YourKeyClass) it.next();

// Refer to the original Hashtable for the

// corresponding value...

YourValue yourValue = (YourValue) someHashtable.get(yourKey);

}

So, not only does it answer the question, it does so in a very terse and elegant manner.

Re: This does not answer the question. Author: Andrew Hart (http://www.jguru.com/guru/viewbio.jsp?EID=935096), Jan 15, 2003Yes, it does. A TreeSet is, by definition, sorted. So, when you construct a TreeSet passing the constructor a collection, it is sorted. If you would like it spelled out: Iterator it = new TreeSet (someHashtable.keySet()).iterator();

while (it.hasNext()) {

// Now, you're reading the key objects in

// the natural sort order...

YourKeyClass yourKey = (YourKeyClass) it.next();

// Refer to the original Hashtable for the

// corresponding value...

YourValue yourValue = (YourValue) someHashtable.get(yourKey);

}

So, not only does it answer the question, it does so in a very terse and elegant manner.

This does not answer the question. Author: chris gutteridge (http://www.jguru.com/guru/viewbio.jsp?EID=1027896), Nov 20, 2002

Page 22: Collections FAQ From jGuru

You say how to get a set out of it, but don't say how to sort that set. so it's not that helpful.

This does not answer the question. Author: chris gutteridge (http://www.jguru.com/guru/viewbio.jsp?EID=1027896), Nov 20, 2002You say how to get a set out of it, but don't say how to sort that set. so it iss not that helpful.

Which collections in Java are synchronized and which aren't?Location: http://www.jguru.com/faq/view.jsp?EID=105899 Created: Jul 19, 2000 Modified: 2000-07-19 12:37:18.569Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Jayaprakash Amballa (http://www.jguru.com/guru/viewbio.jsp?EID=101230

The original collection classes in Java are all synchronized: Vector and Hashtable, along with their subclasses Stack and Properties. Those classes introduced with the Java 2 Collections Framework are all NOT synchronized by default, the sets, lists, and maps. If you need to synchronize those, see How do I synchronize a collection?.

What are the differences between ArrayList and LinkedList? Location: http://www.jguru.com/faq/view.jsp?EID=106663 Created: Jul 20, 2000 Modified: 2000-07-20 07:45:25.631Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Raymond Lui (http://www.jguru.com/guru/viewbio.jsp?EID=72476

An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.

With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.

Which you use really depends on the type of operations you need to support.

Comments and alternative answers

Glen McCluskey posted a Tech Tip titled Using List... Author: Aprameya Paduthonse (http://www.jguru.com/guru/viewbio.jsp?EID=4707), Jan 16, 2001Glen McCluskey posted a Tech Tip titled Using List Collections Efficiently at the JDC that covers this in great detail, including timing differences.

Page 23: Collections FAQ From jGuru

Where can I find Java packages for expressing numerical formulas?Location: http://www.jguru.com/faq/view.jsp?EID=111171 Created: Jul 25, 2000 Modified: 2000-07-25 22:00:45.603Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by ds you (http://www.jguru.com/guru/viewbio.jsp?EID=32792

Colt offers, among others, efficient and usable data structures and algorithms for Off-line and On-line Data Analysis, Linear Algebra, Multi-dimensional arrays, Statistics, Histogramming, Monte Carlo Simulation, Parallel & Concurrent Programming.

Where can I find additional implementations of the Collections Framework API?Location: http://www.jguru.com/faq/view.jsp?EID=114108 Created: Jul 29, 2000 Modified: 2001-07-24 09:33:48.919Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

Doug Lea offers several implementations of collection framework interfaces in his library that help overcome concurrency problems.

You can also check out the Java Collections Clearinghouse.

If you know of any more, please feel free to submit feedback.

Comments and alternative answers

FYI The above link is dead. Author: Spencer Marks (http://www.jguru.com/guru/viewbio.jsp?EID=24112), Oct 28, 2002FYI The above link is dead.

javacollections.org is no longer it seems. Author: Spencer Marks (http://www.jguru.com/guru/viewbio.jsp?EID=24112), Oct 28, 2002FYI The above link is dead.

How do I read input from a stream "one word at a time"?Location: http://www.jguru.com/faq/view.jsp?EID=121065 Created: Aug 7, 2000 Modified: 2001-08-18 17:57:08.874Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Muhammad Qureshi (http://www.jguru.com/guru/viewbio.jsp?EID=87763

What you need to do is use the java.util.StringTokenizer or java.io.StreamTokenizer to parse your input into words. Each has a default set of delimiters like white space that can be changed. The following demonstrates the using of StringTokenizer to count words in a file. import java.io.*;import java.util.*;

Page 24: Collections FAQ From jGuru

public class Test { static final Integer ONE = new Integer(1);

public static void main (String args[]) throws IOException {

Map map = new TreeMap(); FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { processLine(line, map); } printMap(map); } static void processLine(String line, Map map) { StringTokenizer st = new StringTokenizer(line); while (st.hasMoreTokens()) { addWord(map, st.nextToken()); } } static void addWord(Map map, String word) { Object obj = map.get(word); if (obj == null) { map.put(word, ONE); } else { int i = ((Integer)obj).intValue() + 1; map.put(word, new Integer(i)); } } static void printMap(Map map) { Set set = map.entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); System.out.println(entry.getKey() + ": " + entry.getValue()); } }}

Do the keys() and elements() methods of a Hashtable enumerate things in the same order? Location: http://www.jguru.com/faq/view.jsp?EID=123008 Created: Aug 9, 2000 Modified: 2000-08-09 10:10:54.271Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question

Page 25: Collections FAQ From jGuru

originally posed by Nimmi Shamdasani (http://www.jguru.com/guru/viewbio.jsp?EID=91280

There is no requirement that the elements are returned in the same order, only that all of them are returned in the Enumeration. Your best bet for getting the element for a key is to loop through the keys() returned and fetch the element for each. Or, if you can use a HashMap instead of a Hashtable, work with the Map.Entry that is returned by the keySet(). This includes both the key and value together, not requiring a separate lookup.

How do I treat an object I get out of a Vector (collection) as the type I put into it?Location: http://www.jguru.com/faq/view.jsp?EID=207192 Created: Sep 15, 2000 Modified: 2000-09-15 14:09:12.012Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Li Changen (http://www.jguru.com/guru/viewbio.jsp?EID=124609

When you get an object out of a Vector (or any collection), the object is returned as being of type Object. You need to cast it back into the object type you put into the data structure if you need to call or treat the object as the original type.

For instance, if you add an array to a vector:

String args[] = {"1", "2", "3"};Vector v = new Vector();v.addElement(args);Then, when you get the object out of the vector, you need to cast it back to the original type: String args2[] = (String[])v.firstElement();System.out.println(args2.length);

What is the difference between a singly linked list and doubley linked list?Location: http://www.jguru.com/faq/view.jsp?EID=211356 Created: Sep 20, 2000 Modified: 2000-09-20 14:08:56.286Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Prabhakar Pamula (http://www.jguru.com/guru/viewbio.jsp?EID=209916

A singly linked list is one that has only a pointer/reference to the next element in the list. A doubley linked list has both a previous and next pointer/reference.Comments and alternative answers

Single link list is link list in which you can traverse... Author: Rahul kumar Gupta (http://www.jguru.com/guru/viewbio.jsp?EID=4809), Sep 22, 2000Single link list is link list in which you can traverse only in one direction while doubly link list you can traverse in both direction. Here is example - arrows show direction of movement single link listNode 1 -> Node2 -> Node3 ....->Node n

Page 26: Collections FAQ From jGuru

double link list Node 1 <-> Node2 <-> Node3 ....<->Node n

What is a polymorphic algorithm?Location: http://www.jguru.com/faq/view.jsp?EID=213780 Created: Sep 22, 2000 Modified: 2005-08-17 01:43:25.62Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

In general, an algorithm is called polymorphic if it can achieve the same functionality using different data structures. For example, if the same sorting or searching algorithm could be used with different types of containers, such as vectors, lists, maps, etc., then that algorithm would be called polymorphic. As a case in point, the generic algorithms of the STL library in C++ are polymorphic because they can be used for different container classes.

In the context of Java collections, the polymorphic algorithms are all supplied by the various static methods of the java.util.Collections class. Consider, for example, the method sort(List list). This method is capable of sorting any collection that has implemented the List interface, and that includes containers of types ArrayList, LinkedList, Vector, etc.

What is meant by natural ordering of objects in the context of the collections framework? Location: http://www.jguru.com/faq/view.jsp?EID=219388 Created: Sep 29, 2000 Modified: 2005-09-12 13:58:13.706Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

Java documentation refers to the natural ordering of objects when describing various algorithms and data structures in the collections framework. Object ordering is obviously needed by the sorting algorithms. It is also needed by the specifications of the interfaces such as SortedSet, SortedMap, etc., and the data structures used for container classes such as TreeSet, TreeMap, etc. Unless instructed otherwise via a Comparator object supplied as an argument to the constructor, the default behavior of a class such as TreeSet is to store its objects in an ascending natural order.

The objects of a class exhibit natural ordering if the class has implemented the java.lang.Comparable interface. Such a class must provide an implementation for the compareTo method -- referred to as the class's natural comparison method -- that can then be used by the algorithms and the data structures for comparing data objects. The compareTo method must return a negative integer, a zero, or a positive integer if the object on which it is invoked is less than, equal to, or greater than the argument object.

It is strongly recommended that a class's natural ordering as dictated by the implementation of the compareTo method be consistent with equals. This consistency is achieved if and only if e1.compareTo( (Object) e2 ) == 0 has the same boolean value as e1.equals( (Object) e2 ) for every pair of objects e1 and e2 of the class. Lack of this consistency could elicit strange behavior from the data structures that need to compare objects.

Page 27: Collections FAQ From jGuru

Many of the system supplied classes possess natural ordering. These include String, Integer, Float, Double, Date, File and many others. For the String class, the natural order is lexicographic; it is chronological for the Date class; lexicographic on the pathname for the File class, etc.

What is a fail-fast iterator? Location: http://www.jguru.com/faq/view.jsp?EID=221988 Created: Oct 3, 2000 Modified: 2005-08-17 01:37:03.148Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:

1. In multithreaded processing: if one thread is trying to modify a Collection while another thread is iterating over it.

2. In single-threaded or in multithreaded processing: if after the creation of the Iterator, the container is modified at any time by any method other than the Iterator's own remove or add methods.

Note in particular what is implied by the second condition: After we create a container's iterator, during a loop that iterates over the container we must only use the remove (and when applicable add) methods defined for the iterator and that we must NOT use the same methods defined for the container itself. To illustrate this point, suppose we declare and initialize a List in the following manner List list = new ArrayList();list.add("Peter");list.add("Paul");list.add("Mary");Let's say we wish to iterate over this list. We'd need to declare a ListIterator as follows: ListIterator iter = list.listIterator();Having created this iterator, we could now set up a loop like: while(iter1.hasNext()){ String str = iter1.next(); // do something with str}Because iter is fail-fast, we are not allowed to invoke List's add or remove methods inside the loop. Inside the loop, we are only allowed to use ListIterator's add and remove methods. This makes sense because it is the Iterator object that knows where it is in a List as the List is being scanned. The List object itself would have no idea of that.

The Iterators supported by all the work-horse container classes, such as ArrayList, LinkedList, TreeSet, and HashSet, are fail-fast. The Iterator type retrofitted to the older container class Vector is also fail-fast. For associative containers, such as HashMap and the older HashTable, the Iterator type for the Collections corresponding to either the keys or the values or the <key, value> pairs are fail-fast with respect to the container itself. That means that even if you are iterating over, say, just the keys of the container, any illegal concurrent modifications to the underlying container would be detected.

One final note regarding iterators versus enumerations: It is also possible to use an Enumeration object returned by the elements() method for iterating over the older container types such as Vector. However, Enumerations do not provide a fail-fast method. On the other hand, the more modern Iterator returned by a Vector's

Page 28: Collections FAQ From jGuru

iterator() and listIterator() methods are fail-fast. Hence, iterators are recommended over enumerations for iterating over the elements of the older container types.

Comments and alternative answers

fail-fast iterators are not guaranteed to detect concurrent modifications Author: Steven Feist (http://www.jguru.com/guru/viewbio.jsp?EID=966332), Jul 26, 2002This item implies that fail-fast iterators will always detect concurrent modifications, but this is not the case: they throw ConcurrentModificationException on a "best-effort" basis. See http://java.sun.com/j2se/1.4/docs/api/java/util/ConcurrentModificationException.html.

How do you sort the elements of a vector?Location: http://www.jguru.com/faq/view.jsp?EID=223115 Created: Oct 5, 2000 Modified: 2001-02-06 19:46:13.185Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Ravi Sankar Kavula (http://www.jguru.com/guru/viewbio.jsp?EID=222405

Since the Vector class implements the List interface, you can call the Collections.sort() method to sort the elements in place. You can also manually insert elements into a Vector to keep the vector sorted. Of course, if keeping sorted access is such a big deal, you should consider using a different, more appropriate data structure like a TreeSet.

For 1.1 Java users, you'll need to sort the elements yourself. There is no built-in support for this. A better option might be to sort the elements as you insert each element.

What is stable sorting? Location: http://www.jguru.com/faq/view.jsp?EID=225366 Created: Oct 9, 2000 Modified: 2005-08-15 12:58:19.757Author: Avi Kak (http://www.jguru.com/guru/viewbio.jsp?EID=26410)

The collections framework specification requires that the sorting algorithms be stable. Stated succinctly, a sorting algorithm is stable if it does not reorder equal elements. But what does that really mean? The goal of this posting is to illustrate this concept.

Stability in sorting becomes an issue for class-type objects with two or more data members. We'd obviously need to choose a data member whose values will be used to order the objects for sorting. Let's say we have multiple objects in a list whose values for the data member chosen for comparison are the same, but whose values for the other data members are different. A stable sorting algorithm will leave the original order of such objects untouched.

Stability in sorting, or lack thereof, is best illustrated by comparing the sorted order obtained through the quicksort algorithm with the sorted order obtained through the mergesort algorithm. An optimized implementation of quicksort is slightly faster than

Page 29: Collections FAQ From jGuru

an optimized implementation of mergesort but does not guarantee stability. On the other hand, mergesort guarantees stability.

To show the comparative results obtained with quicksort and mergesort, let's define the following class:

class Person { String name; int rank; Person( String nam, int r ) { name = new String( nam ); rank = r; } String getName() { return name; }; public String toString() { return name + " " + rank; }}We will sort Person objects by using the following Comparator object: class PersonComparator implements Comparator {

public int compare( Object o1, Object o2 ) { Person p1 = ( Person ) o1; Person p2 = ( Person ) o2; return p1.getName().compareTo( p2.getName() ); }}This will compare Person objects on the basis of the name field. For the purpose of sorting, let's now construct a list of Person objects by List perList = new ArrayList();

perList.add( new Person( "Zaphod", 0 ) ); perList.add( new Person( "Zaphod", 1 ) ); perList.add( new Person( "Zaphod", 2 ) ); perList.add( new Person( "Betelgeuse", 0 ) ); perList.add( new Person( "Betelgeuse", 1 ) ); perList.add( new Person( "Betelgeuse", 2 ) ); perList.add( new Person( "Trillion", 0 ) ); perList.add( new Person( "Trillion", 1 ) ); perList.add( new Person( "Trillion", 2 ) );A stable sorting algorithm will reorder the names in the list, but for each name will leave untouched the order of appearance with respect to the rank. We can sort this list by a mergesort algorithm by invoking Collections.sort( perList, new PersonComparator() );The sorted listed will be as follows:

Betelgeuse 0 Betelgeuse 1 Betelgeuse 2 Trillion 0 Trillion 1 Trillion 2 Zaphod 0 Zaphod 1 Zaphod 2where the name is followed by the associated rank in each Person object.

Page 30: Collections FAQ From jGuru

On the other hand, if we sort the same original list with a quicksort algorithm using again the name field for comparison, we get

Betelgeuse 0 Betelgeuse 2 Betelgeuse 1 Trillion 2 Trillion 0 Trillion 1 Zaphod 0 Zaphod 2 Zaphod 1

Notice that objects that are equal with respect to the name field are getting shuffled by the quicksort algorithm.

The quicksort results I showed above were obtained with a C++ program that invoked the well-known qsort function with the following invocation

qsort( perList, 9, sizeof( Person* ), comparePersons );where the list of Person objects was declared as

Person* perList[9];

with each element of the list instantiated by a statement like perList[0] = new Person( "Zaphod", 0 ); perList[1] = new Person( "Zaphod", 1 ); ... ...The comparison function needed for the fourth argument of qsort was defined by

int comparePersons( const void* arg1, const void* arg2 ){ string str1 = (*( Person** )arg1)->name; string str2 = (*( Person** )arg2)->name; return ( str1 ).compare( str2 );}

What is a WeakHashMap? What is its use and when should you use it?Location: http://www.jguru.com/faq/view.jsp?EID=229560 Created: Oct 16, 2000 Modified: 2001-04-19 21:00:00.756Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by piyush sheth (http://www.jguru.com/guru/viewbio.jsp?EID=38282

A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren't used elsewhere may be dropped with no side effects. Also, just because a key may be dropped, doesn't mean it will immediately be dropped. If the system has sufficient resources, the weak key reference that isn't externally referenced could stay around for a long time.

Page 31: Collections FAQ From jGuru

For additional information on Reachability, you can find it in the java.lang.ref package summary.

Comments and alternative answers

That's almost completely bogus. Here's a better an... Author: Kevin Riff (http://www.jguru.com/guru/viewbio.jsp?EID=2057), Nov 8, 2000That's almost completely bogus. Here's a better answer:

WeakHashMap is a special implementation of the Map interface that references its keys via weak references. This allows the garbage collector to reclaim the key even though its still referenced by the hashmap. If the garbage collector does reclaim the key then WeakHashMap automatically cleans out the key and its associated value.

WeakHashMaps work best when the keys are objects which are equal only to themselves. This is the default implementation in the Object class and is sometimes called "identity equality". If the keys implement "value equality" (where the equals method compares the object's contents, not their references) then you can sometimes observe odd behavior. In particular, if you attempt to lookup a value using a different but equal key you may find that the WeakHashMap no longer has a mapping for it. This would happen if the original key was dereferenced and garbage collected prior to your search.

A good example of WeakHashMap in action is the ThreadLocal class. ThreadLocal uses a WeakHashMap internally where the keys are Threads. When you call get(), the ThreadLocal class gets a reference to the current thread and looks up its value in the WeakHashMap. When the thread dies, it becomes unreachable and the WeakHashMap automatically removes its mapping. If ThreadLocal used a regular HashMap, then the Threads stored in it would never become unreachable and they could hang around for a long, long time. This would essentially be a memory leak.

Re: That's almost completely bogus. Here's a better an... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 24, 20011.3 does not use a WeakHashMap with ThreadLocal, only 1.2 did. And as of 1.4, ThreadLocal uses an IdentifyHashMap.

Re: Re: That's almost completely bogus. Here's a better an... Author: Kevin Riff (http://www.jguru.com/guru/viewbio.jsp?EID=2057), Jul 25, 2001You're right. I checked 1.3 and see that instead of a WeakHashMap where the threads are the keys, it uses a standard HashMap in each Thread object where the keys are the ThreadLocal objects (actually they use a hack that

Page 32: Collections FAQ From jGuru

approximates the behaviour of an IdentityHashMap to prevent spoof attacks). It's a much better design because it eliminates the thread contention on the ThreadLocal's lock. I haven't looked at the JDK 1.4 source code yet, but I imagine it uses an IdentityHashMap in order to drop the ugly hack.

In my defense I can only say that I probably only had JDK 1.2.2 to use in my investigations. I can't be held responsible if Sun changed the implementation. Besides, I only used ThreadLocal as an example because I can't think of any other situation where you would want to use a WeakHashMap.

PS - Please forgive the tone of my previous post. I was obviously in a very foul mood that day. I can't seem to remember what it was that I found so objectionable in the original answer.

See also... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 24, 2001What is a weak reference and what are they used fo...

Re: See also... Author: lang qiu (http://www.jguru.com/guru/viewbio.jsp?EID=518165), Apr 15, 2003Read the article from the OnJava about the WeakHashMap http://www.onjava.com/lpt/a/989

Re: See also... Author: lang qiu (http://www.jguru.com/guru/viewbio.jsp?EID=518165), Apr 15, 2003Read the article from the OnJava about the WeakHashMap http://www.onjava.com/lpt/a/989

Re: See also... Author: lang qiu (http://www.jguru.com/guru/viewbio.jsp?EID=518165), Apr 15, 2003Read the article from the OnJava about the WeakHashMap http://www.onjava.com/lpt/a/989

What is the function of a load factor in a Hashtable? Location: http://www.jguru.com/faq/view.jsp?EID=246454 Created: Nov 6, 2000 Modified: 2000-11-06 09:37:38.855Author: Jef Newsom (http://www.jguru.com/guru/viewbio.jsp?EID=129583) Question originally posed by Siddhartha Mehta (http://www.jguru.com/guru/viewbio.jsp?EID=235146

Page 33: Collections FAQ From jGuru

The load factor determines how full a hashtable may get before it expands its capacity. I think that the comments on the Hashtable API docs explain it very well:

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method.

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

How do you control growth of vectors when their internal arrays are full?Location: http://www.jguru.com/faq/view.jsp?EID=262290 Created: Nov 24, 2000 Modified: 2000-11-24 21:37:34.895Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The vector constructor can include either an initial capacity or a capacity and growth increment. When not specified, the initial size of the vector is 10 and growth will double when necessary. Otherwise, initialize size and growth will grow when needed as specified by the arguments to the constructor.

If the argument to the constructor is a collection, the initial size of the internal structure is 10% larger than the collection. Since there is no second argument to control growth, the capacity will double when necessary.

How to sort the messages in JavaMail?Location: http://www.jguru.com/faq/view.jsp?EID=266225 Created: Nov 30, 2000 Modified: 2000-11-30 09:31:57.594Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by guan ho (http://www.jguru.com/guru/viewbio.jsp?EID=126860

Within the JavaMail classes there is no support for this. However, once you get the array of messages back from a folder, you can call the Arrays.sort() method in the collections framework to sort the messges. Since MimeMessage doesn't implement Comparable, you'll need to provide your own Comparator specifying how you want the messages to be sorted.Comments and alternative answers

Could you post some example code on this....? Author: Kevin Baker (http://www.jguru.com/guru/viewbio.jsp?EID=882634), Oct 9, 2002Could you post some example code on this....?

Re: Could you post some example code on this....? Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Oct 9, 2002The Compartor interface requires you to implement the compareTo method, which accepts two args (the messages to compare for here). Compare the two fields of the message you want to sort by. If message1 comes first, return -1, if equal, return 0, if message2 comes first, return 1.

Page 34: Collections FAQ From jGuru

When did Strings start caching their hash codes?Location: http://www.jguru.com/faq/view.jsp?EID=289946 Created: Dec 30, 2000 Modified: 2000-12-30 19:27:02.099Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Starting with the 1.3 release of Java, the java.lang.String class will only calculate the hashcode once, when its first needed. Future calls to hashCode() will return the previously calculated value.

How can you retrieve the Hashtable's load factor?Location: http://www.jguru.com/faq/view.jsp?EID=302158 Created: Jan 14, 2001 Modified: 2001-01-14 09:16:51.742Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Jen Ngew (http://www.jguru.com/guru/viewbio.jsp?EID=302138

There is no public interface to access the load factor setting.

Some choices you can do to expose this value...

Subclass Hashtable and add a read-only accessor method Use reflection to access the private field (only possible in trusted

environment) Serialize the Hashtable and get the value from the stream (when reading back

the stream, you'll have to figure out where the appropriate field is)

Why can't I add a collection to itself?Location: http://www.jguru.com/faq/view.jsp?EID=302736 Created: Jan 15, 2001 Modified: 2001-01-15 08:03:53.163Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This will cause a stack overflow exception to be generated on calls to methods like toString() and hashCode(), which recursively call the method on the elements of the collection.

What is meant by compatible equals() and hashCode() methods?Location: http://www.jguru.com/faq/view.jsp?EID=302746 Created: Jan 15, 2001 Modified: 2001-01-15 08:08:21.172Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

In order for the Java Collections to work properly (and everything else in Java), the equals() and hashCode() methods must be compatible. Here, compatible means that if equals() reports that two instances are the same, then the hashCode() of both instances must be the same value.

Since Properties extends Hashtable, can I use the Hashtable methods to add elements to a Properties list?Location: http://www.jguru.com/faq/view.jsp?EID=302764 Created: Jan 15, 2001 Modified: 2001-01-15 08:17:43.611Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Technically speaking you can. However, you have to make sure you only add key-value pairs where both are strings. If you add something other than a String, the listing, loading, and saving methods won't work as expected.

Page 35: Collections FAQ From jGuru

Like the Stack/Vector subclass relationship, Properties/Hashtable should be a has-a relationship, not an is-a/subclass relationship.

When I wrap a collection to be read-only or synchronized, why can't I call any of the collection methods via reflection without getting an IllegalAccessException?Location: http://www.jguru.com/faq/view.jsp?EID=304724 Created: Jan 17, 2001 Modified: 2001-01-17 05:30:21.271Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Brandon Wiley (http://www.jguru.com/guru/viewbio.jsp?EID=304445

When you wrap a collection through the static methods of the Collections class, this creates an instance of a package-private (default access) class. Because you don't have access to these classes, you can't call their methods via reflection (though you can call their methods directly through the appropriate interface).

What is a weak reference and what are they used for?Location: http://www.jguru.com/faq/view.jsp?EID=316912 Created: Jan 30, 2001 Modified: 2001-01-31 05:50:05.975Author: Rob Wilson (http://www.jguru.com/guru/viewbio.jsp?EID=313998) Question originally posed by Ravikumar Gopalankutty (http://www.jguru.com/guru/viewbio.jsp?EID=32913

Normally the Java garbage collector plays safe. It will only free up the memory used by an object when that object can no longer be accessed by the program. Once an object become impossible to reach it is eligible for collection, and eventually its memory will be reclaimed.

This eliminates one of the most common programming errors in some other languages (like C++), where code accidentally tries to access an object that has been freed. Unfortunately it can lead to another problem, where you leave open a potential access route to an object that you don't need any more. Memory fills up, and the program slows down or reports an "Out of Memory" error.

To avoid this, you can be very careful to close off access paths to an object once you have finished using it. Java 2 introduces another alternative, the weak reference. Weak references provide access to an object without preventing it from being freed. When you use a weak reference you have to accept that the object referred to may have disappeared, which results in the reference being automatically set to null. On the other hand, the weak reference will not hold the object in memory once it is inaccessible via normal references (or via "soft" references - see below). Weak references are not appropriate in all circumstances, but sometimes they can make code easier to write and understand.

The most common use of weak references is indirect - they are used internally by the WeakHashMap class. Like HashMap, WeakHashMap associates key objects with values. However, once the key object becomes inaccessible via stronger references it becomes eligible for garbage collection. When it is freed, the map entry magically disappears. The assumption here is that if you are not using the key anywhere other than in the map you will have no need to look it up, so it should be freed.

Other specialist references are soft references (which inhibit collection until memory runs short), and phantom references (used for cleanup when objects are freed).

Page 36: Collections FAQ From jGuru

For more detailed (and precise) information, see the java.lang.ref API docs, and also the article Reference Objects and Garbage Collection at the Sun website.

Comments and alternative answers

See also... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jul 24, 2001What is a WeakHashMap? What is its use and when sh...

What is the minimum number of key-value pairs for which it makes sense to use a HashMap, as opposed to using a pair of arrays (one for keys, the other for values) with brute-force key searches?

Many people often need maps for very small numbers (2-5) of key-value pairs. When does it make sense to forgo the convenience of the HashMap to avoid the associated overhead?

Location: http://www.jguru.com/faq/view.jsp?EID=329390 Created: Feb 14, 2001 Modified: 2001-02-14 21:02:25.101Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212) Question originally posed by Michael Wax (http://www.jguru.com/guru/viewbio.jsp?EID=242559

Well, is there really that much of a performance loss using a HashMap? There is no synchronization penalty (unless you impose your own). You can tune the sizing by adjusting the initial size and load factor. Plus, do you really want to be responsible for "rolling your own" code to handle the dynamic resizing of the key and value arrays, inserting/removing data from these arrays, optimizing the searching algorithm, etc. Yuck!

In general, the performance hit associated with using a general purpose Map (such as the HashMap) is far outweighed by the benefits of using a simple interface backed by a tested algorithm.

The only reason I could see wanting to use arrays is to guaruntee the type of your key/values to add type checking and avoid casting. Still, if this is a critical aspect of your application, you can wrap your HashMap in another object to provide type-safety, and the casting overhead should be minimal.

Another alternative to creating a custom solution is to explore other collection classes, such as ObjectSpaces's JGL Libraries. There may be something there that would suit your needs.

So, to answer your question, I would say that the fewer the key-value pairs you have, the more reason you have to use a HashMap. Since the fewer the keys, the faster the search, why not use it for 2-5 key-value pairs. I would think that only when you get to many pairs (tens of thousands) and there is a performance problem you should consider an alternative. Basically, exhaust your search of tried-and-true collections before you try a custom solution. Let other people create these collections so you can focus on your application.

Page 37: Collections FAQ From jGuru

[Editor note: HashMaps of 10K pairs will function fine, assuming a good hashing algorithm for hashCode() [with evenly spread out keys]. Keep using it at 10K and beyond with no problems.]

How does ArrayList increase its capacity?Location: http://www.jguru.com/faq/view.jsp?EID=333358 Created: Feb 19, 2001 Modified: 2001-02-19 13:32:49.494Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Unlike Vector where you can specify a capacity increment, ArrayList doesn't support this. Instead, ArrayList will increase capacity by about a half when it runs out of space. The refernece implementation uses the forumla: newCapacity = (oldCapacity * 3)/2 + 1though, this isn't part of the class definition so others can implement it differently.

How can I implement a priority queue in Java? Has anyone created an open source version?Location: http://www.jguru.com/faq/view.jsp?EID=335988 Created: Feb 22, 2001 Modified: 2001-07-24 09:53:00.176Author: michele arpaia (http://www.jguru.com/guru/viewbio.jsp?EID=227978) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

As referenced from the Java Collections Clearinghouse, you can find a priority queue implemented as part of MIT's FLEX compiler imfrastructure. Source code is licensed under the GNU GPL.

There is also source for one in my Java Collections book.

What is the default initial size for a Hashtable / HashMap?Location: http://www.jguru.com/faq/view.jsp?EID=338326 Created: Feb 25, 2001 Modified: 2001-02-25 14:24:21.043Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

This depends on what version of Java you are using. For JDK 1.2, the size was 101. For JDK 1.3, the size changed to 11.

How do you create a multi-dimensional List?Location: http://www.jguru.com/faq/view.jsp?EID=353663 Created: Mar 17, 2001 Modified: 2001-03-17 04:26:35.939Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Pankaj Sud (http://www.jguru.com/guru/viewbio.jsp?EID=280230

Since the elements of a List are objects, in order to make the List multi-dimensional, each object in the outer list needs to be a List, too. For instance, ...

List list = new ArrayList(10);for (int i=0; i<10; i++) { list.set(i, new LinkedList());}Then just fill up each inner list with items.

Page 38: Collections FAQ From jGuru

In a TreeMap, can I use a sorting algorithm other than the natural sorting for the keys? Location: http://www.jguru.com/faq/view.jsp?EID=396730 Created: Apr 5, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Shailesh Mangal (http://www.jguru.com/guru/viewbio.jsp?EID=57184

You can pass a Comparator to the TreeMap constructor to use a sorting order other than the natural order.

What are the differences between HashMap and Hashtable?Location: http://www.jguru.com/faq/view.jsp?EID=430247 Created: May 29, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by elango maragtham (http://www.jguru.com/guru/viewbio.jsp?EID=248437

Both provide key-value access to data. The Hashtable is one of the original collection classes in Java. HashMap is part of the new Collections Framework, added with Java 2, v1.2.

The key difference between the two is that access to the Hashtable is synchronized on the table while access to the HashMap isn't. You can add it, but it isn't there by default.

Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't. If you change the map while iterating, you'll know.

And, a third difference is that HashMap permits null values in it, while Hashtable doesn't.

For new code, I would tend to always use HashMap.

Comments and alternative answers

What is synchronize in this context? What is fail-safe property? Author: Bhuricha S. (http://www.jguru.com/guru/viewbio.jsp?EID=1029536), Nov 23, 2002I am sorry for asking easy question. I wonder when will the synchronized object be useful? Can you give me some example? And what is the fail-safe in this context. Is there any reference where I can read more about it? Thanks

Re: What is synchronize in this context? What is fail-safe property? Author: Dheerendra Pandey (http://www.jguru.com/guru/viewbio.jsp?EID=1224636), Feb 2, 20051)Synchronized means only one thread can modify a hash table at one point of time.Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Page 39: Collections FAQ From jGuru

2)Fail-safe is relevant from the context of iterators.If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally",a concurrent modification exception will be thrown.It is possible for other threads though to invoke "set" method since it doesnt modify the collection "structurally".However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.

What is synchronize in this context? What is fail-safe property? Author: Bhuricha S. (http://www.jguru.com/guru/viewbio.jsp?EID=1029536), Nov 23, 2002I am sorry for asking easy question. I wonder when will the synchronized object be useful? Can you give me some example? And what is the fail-safe in this context. Is there any reference where I can read more about it? Thanks

Null Values Author: Sujatha Vengaiah (http://www.jguru.com/guru/viewbio.jsp?EID=1054003), Feb 5, 2003Hashtable doesnt allow NULL Values...does it mean for both key and value or just the key....

Re: Null Values Author: Zia Raees (http://www.jguru.com/guru/viewbio.jsp?EID=1175092), May 31, 2004It means that the hashtable cannot have null value across a key.

Re: Null Values Author: keertikar pandey (http://www.jguru.com/guru/viewbio.jsp?EID=1177623), Jun 10, 2004Key field should never be null , because only on basis of keys , one can access the corresponding values.

Re: Null Values Author: keertikar pandey (http://www.jguru.com/guru/viewbio.jsp?EID=1177623), Jun 10, 2004Key field should never be null , because only on basis of keys , one can access the corresponding values.

Null Values Author: Sujatha Vengaiah (http://www.jguru.com/guru/viewbio.jsp?EID=1054003), Feb 5, 2003Hashtable doesnt allow NULL Values...does it mean for both key and value entry or just the key entry....

Re: Null Values Author: Shamit Sen (http://www.jguru.com/guru/viewbio.jsp?EID=1160219), Apr 5, 2004

Page 40: Collections FAQ From jGuru

Hashtable does not permit null values for the keys

Re: Null Values Author: Shamit Sen (http://www.jguru.com/guru/viewbio.jsp?EID=1160219), Apr 5, 2004Hashtable does not permit null values for the keys.

Where can I learn (more) about Java's support for developing multi-threaded programs? Location: http://www.jguru.com/faq/view.jsp?EID=431248 Created: May 30, 2001 Author: John Mitchell (http://www.jguru.com/guru/viewbio.jsp?EID=4)

Check out the jGuru Threads FAQ.

What are the differences between Vector and ArrayList? Which is best to use?Location: http://www.jguru.com/faq/view.jsp?EID=433158 Created: Jun 3, 2001 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by elango maragtham (http://www.jguru.com/guru/viewbio.jsp?EID=248437

Vector and ArrayList are very similar. Both of them represent a 'growable array', where you access to the elements in it through an index.

ArrayList it's part of the Java Collection Framework, and has been added with version 1.2, while Vector it's an object that is present since the first version of the JDK. Vector, anyway, has been retrofitted to implement the List interface.

The main difference is that Vector it's a synchronized object, while ArrayList it's not.

While the iterator that are returned by both classes are fail-fast (they cleanly thrown a ConcurrentModificationException when the orignal object has been modified), the Enumeration returned by Vector are not.

Unless you have strong reason to use a Vector, the suggestion is to use the ArrayList.Comments and alternative answers

OnJava.com article... Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7), Jun 18, 2001For additional information, you can read an article comparing the performance at The Performance of Java's Lists.

Not Satisfied Author: kapil pruthi (http://www.jguru.com/guru/viewbio.jsp?EID=909671), Jun 11, 2002totally not satisfied with the answer provided.please elaborate..

Page 41: Collections FAQ From jGuru

Java.util.Collection Author: Rohit Anand (http://www.jguru.com/guru/viewbio.jsp?EID=1088769), Oct 31, 2003one more difference can be ArrayList implements Iterator Interface for traversing While Vector implements Innumerator Interface for traverse.

here is the elaborate answer Author: san mack (http://www.jguru.com/guru/viewbio.jsp?EID=1124796), Mar 23, 2004Sometimes Vector is better; sometimes ArrayList is better; sometimes you don't want to use either. I hope you weren't looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider: API Synchronization Data growth Usage patterns Let's explore each in turn. API In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes. Synchronization Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily? Data growth Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value. Usage patterns Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time -- O(1). However, adding and removing elements from any other position proves more expensive -- linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean? It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time -- O(1). However, indexing an element is a bit slower -- O(i) where i is the index of the element. Traversing an ArrayList is

Page 42: Collections FAQ From jGuru

also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created. Finally, in "PRAXIS 41" from Practical Java (Addison-Wesley, Feb. 2000) Peter Haggar suggests that you use a plain old array in place of either Vector or ArrayList -- especially for performance-critical code. By using an array you can avoid synchronization, extra method calls, and suboptimal resizing. You just pay the cost of extra development time.

Another Difference Author: shreehari gopal (http://www.jguru.com/guru/viewbio.jsp?EID=1163112), May 18, 2004There is also an another difference between Vectors and ArrayLists, not very important but it will be an added advantage. If we insert an element beyond the border of a vector it will increases the size by double of its orginal size.but an ArrayList will increases its size by 50% of the orginal list

How should I implement object comparisons in a flexible manner? For example, I have a Person class and sometimes I will compare based on name and sometimes I will compare based on age.Location: http://www.jguru.com/faq/view.jsp?EID=447904 Created: Jun 29, 2001 Modified: 2005-09-12 13:10:30.244Author: Ryan Breidenbach (http://www.jguru.com/guru/viewbio.jsp?EID=45212) Question originally posed by yangontha Maung (http://www.jguru.com/guru/viewbio.jsp?EID=427789

Instead of having the Person class implement the Comparable interface, you could delegate the comparing to another class. Perhaps you could have a PersonComparator interface that you could implement for the various types of comparisons. For example: public interface Person { public String getName(); public int getAge();}

public interface PersonComparator { public int compare(Person p1, Person p2);}

public class AgeComparator implements PersonComparator { public int compare(Person p1, Person p2) { if (p1.getAge() == p2.getAge()) return 0; return p1.getAge() > p2.getAge() ? 1 : -1; }}

public class NameComparator implements PersonComparator { public int compare(Person p1, Person p2) { return p1.getName().compareTo(p2.getName()); }}This is a very simple example of the Strategy Pattern. This allows your comparisons and your object to change independent of one another.

Page 43: Collections FAQ From jGuru

Comments and alternative answers

Additional Information Author: christophe tcheng (http://www.jguru.com/guru/viewbio.jsp?EID=269636), Jul 2, 2001

You should consider implementing the Comparator interface (java.util), and not your own PersonComparator interface. Indeed, this interface is known used in the JDK, and therefore you will be able to sort arrays or collections very easily.

Collections.sort( ... );

Arrays.sort( ... );

Christophe.

Just use the standard Comparable interface + get/setSort methods. Author: Cat Cat (http://www.jguru.com/guru/viewbio.jsp?EID=462569), Jul 26, 2001

You can hide the implementation details inside the class and just change the way the data is sorted with get/set methods.

public class Person implements Comparable{ private static final int NAMESORT = 0; private static final int AGESORT = 1; private int m_nSort = NAMESORT;

public int compareTo(Object obj){ int nComparison = 0;//equal default

//probably use switch here for //more complex cases if(m_nSort == NAMESORT){ //code to sort by name } else{ //code to sort by age } return nComparison; }

public void setSort(int nSort){ if((nSort > 0)&&(nSort <= AGESORT)){ m_nSort = nSort; } } public int getSort(){ return m_nSort; }}

Page 44: Collections FAQ From jGuru

Thanks for the question it helped to clarify a problem I was trying to solve. Cat

Re: Just use the standard Comparable interface + get/setSort methods. Author: Cat Cat (http://www.jguru.com/guru/viewbio.jsp?EID=462569), Jul 26, 2001

Should obviously be......

.. public static final int NAMESORT = 0; public static final int AGESORT = 0;..

Not

... private static final int NAMESORT = 0; private static final int AGESORT = 1;...

Cat

Re: Just use the standard Comparable interface + get/setSort methods. Author: Gaddy Barchana Lorand (http://www.jguru.com/guru/viewbio.jsp?EID=230945), Aug 13, 2001That might cause some problems. What happens when you sort the same objects concurrently (e.g. sorting two arrays that have the same entries, each with tis sorting order).

You can get situations where a.compareTo(b) and b.compareTo(a) are inconsistent (if a and b were called with different sort methods).

Re: Re: Just use the standard Comparable interface + get/setSort methods. Author: Cat Cat (http://www.jguru.com/guru/viewbio.jsp?EID=462569), Aug 13, 2001

Good point. My response would be to make certain that you could only compare apples with apples.

One way to handle this would be to override the compareTo method so that it used the getSort method to check the sort type and threw an

Page 45: Collections FAQ From jGuru

IllegalArgumentException if they where different.

My personal opinion is that it represents the simplest solution to the problem. And given the flexablility of the compareTo method I doubt that you would have a situation in which it definitively couldn't be solved this way.

It is nice to have a general purpose framework like this. It certainly saves you from having to do your own sorting algorithms 95% of the time. Which for mere mortals is a real pain.

Cat

Does the equals() method of an array do element-level checking?Location: http://www.jguru.com/faq/view.jsp?EID=454787 Created: Jul 14, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

If you have two arrays in memory with the same elements, and ask first.equals(second), this does not do an element-by-element comparison. Instead, it behaves just like Object's equals() method, essentially asking if the variables point to the same place in memory: int a[] = {1, 2, 3}; int b[] = {1, 2, 3}; // This prints false System.out.println(a.equals(b));To check for equality of two arrays, use Arrays.equals(). // This prints true System.out.println(Arrays.equals(a,b));Comments and alternative answers

How about "==" operator of an array? Author: Michael Guo (http://www.jguru.com/guru/viewbio.jsp?EID=748914), Feb 6, 2002According to this, the "==" operator and "equals()" method should work same for array. Is that right?Then how about for String?

Re: How about "==" operator of an array? Author: ashwini iyer (http://www.jguru.com/guru/viewbio.jsp?EID=1170181), May 12, 2004for a string == does a reference checking and .equals() matches the exact words

How can I retrieve the items in my HashSet / HashMap in the order they were added?

Page 46: Collections FAQ From jGuru

Location: http://www.jguru.com/faq/view.jsp?EID=456424 Created: Jul 17, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Prior to Java 1.4, you had to manage a separate insertion order list yourself. Starting with Java 1.4, you can use the new LinkedHashMap / LinkedHashSet classes. The iterators you get back from them return the items in insertion order.Comments and alternative answers

Give me an example Author: James Liu (http://www.jguru.com/guru/viewbio.jsp?EID=1032513), Dec 1, 2002Please give me an examole for the answer.

An Example Author: Shiladitya Sircar (http://www.jguru.com/guru/viewbio.jsp?EID=1173860), May 26, 2004LinkedHashMap is essentially similar to the LinkedHashSet, its just that you need a key/value pair for each element. Example : String Englishmonths[] = new DateFormatSymbols().getMonths(); String frenchMonths[] = new DateFormatSymbols(Locale.ITALIAN).getMonths(); Map orderedMap = new LinkedHashMap(); for (int i = 0, n = months.length; i & lt; n; i++) { orderedMap.put(months[i], italianMonths[i]); }

Check to see that iterators for this are aware of the insertion order. So you can walk through the values of the insertion order. Collection values = orderedMap.values(); for (Iterator i = values.iterator(); i.hasNext(); { System.out.println(i.next())); }

How do you sort an ArrayList (or any list) of user-defined objects?Location: http://www.jguru.com/faq/view.jsp?EID=461146 Created: Jul 24, 2001 Modified: 2001-11-29 22:44:12.608Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by Anup Darvatkar (http://www.jguru.com/guru/viewbio.jsp?EID=454475

Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

See also: Sort algorithm on an ArrayList.

How can you get the hash code for an instance of a class if the class overrode hashCode()?Location: http://www.jguru.com/faq/view.jsp?EID=470503

Page 47: Collections FAQ From jGuru

Created: Aug 7, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The System class method identityHashCode() allows you to get this information:

int code = System.identityHashCode(anObject);

Comments and alternative answers

HashCode Author: Parag Agarwal (http://www.jguru.com/guru/viewbio.jsp?EID=1136228), Dec 30, 2003

YourClass obj;

System.out.println(obj.hashCode());

has nothing to do with Collections .... Author: Yilmaz Mete (http://www.jguru.com/guru/viewbio.jsp?EID=1250231), Jun 24, 2005Object.hashCode() is the method otherwise.

How can I easily shift the elements in a List / Vector such that all the elements rotate n elements?Location: http://www.jguru.com/faq/view.jsp?EID=483403 Created: Aug 24, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The Java 1.4 API adds a rotate() method to the Collections class: rotate(List list, int distance) that will shift the elements for you.

What's the most optimum way of swapping two elements in a List?Location: http://www.jguru.com/faq/view.jsp?EID=483410 Created: Aug 24, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The 1.4 version of Collections has a swap() method to do this for you. However, for earlier version of Java, you can swap two elements w/o an intermediate variable with:list.set(index1, list.set(index2, list.get(index1)));

This works because the set() method returns the original element.

What's the purpose of the IdentityHashMap?Location: http://www.jguru.com/faq/view.jsp?EID=483413

Page 48: Collections FAQ From jGuru

Created: Aug 24, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both performance reasons, if you know that two different elements will never be equals and for preventing spoofing, where an object tries to imitate another.

How do I convert an old-style Enumeration to something in the Collections Framework?Location: http://www.jguru.com/faq/view.jsp?EID=485886 Created: Aug 28, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Prior to Java 1.4, any conversion had to be manually done. With the introduction of 1.4, you can call Collections.list(enumeration) to automatically convert the Enumeration to an ArrayList.

How do I retrieve the values of a Hashtable/HashMap in sorted order?Location: http://www.jguru.com/faq/view.jsp?EID=503126 Created: Sep 25, 2001 Modified: 2001-11-29 22:45:37.037Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Ajay Tejwani (http://www.jguru.com/guru/viewbio.jsp?EID=418246

Basically, you can't directly do this. What you can do is get the Collection of values() back from the map and create a sorted collection, or maintain two maps, one in each direction, and keep the second map sorted by being a TreeMap. Which you use depends on the frequency you must sort the elements.Comments and alternative answers

Sorted Hashtable Author: Sualeh Fatehi (http://www.jguru.com/guru/viewbio.jsp?EID=404605), Jun 4, 2002Here is something you may be able to use - you will have to do your own debugging, though ;-) import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;

/** * @author Sualeh Fatehi */public class SortedHashtable{

protected Hashtable hashSortedHashtable = new Hashtable(); protected Vector vectSortedHashtable = new Vector();

public Enumeration keys()

Page 49: Collections FAQ From jGuru

{

return vectSortedHashtable.elements();

}

public void clear() {

hashSortedHashtable = new Hashtable(); vectSortedHashtable = new Vector();

}

public synchronized void put(String key, Entity value) {

boolean bSorted = false;

for (int i = 0; i < vectSortedHashtable.size(); i++) { Entity base = (Entity) hashSortedHashtable.get(vectSortedHashtable.elementAt(i)); if (base.compareTo(value) > 0) { vectSortedHashtable.insertElementAt(key, i); bSorted = true; break; } } if (!bSorted) { bSorted = true; vectSortedHashtable.addElement(key); } hashSortedHashtable.put(key, value);

}

protected synchronized void internalPut(String key, Entity value) {

vectSortedHashtable.addElement(key); hashSortedHashtable.put(key, value);

}

public Entity get(String key) {

return (Entity) hashSortedHashtable.get(key);

}

Page 50: Collections FAQ From jGuru

public synchronized void remove(String key) { vectSortedHashtable.remove(key); hashSortedHashtable.remove(key); }

} // end SortedHashtable

Re: Sorted Hashtable Author: manish janjani (http://www.jguru.com/guru/viewbio.jsp?EID=1184790), Jul 8, 2004

Can u provide me some simpler solution to get the values from a hash map? The method u hav given is quiet confusing. My need is to read a text file which can be used as a cinfig file. The file will hav some options as true and false or something like that. so m looking for a solution which is smaller and as desired. Thnks

Sorted Hashtable Author: Sualeh Fatehi (http://www.jguru.com/guru/viewbio.jsp?EID=404605), Jun 4, 2002Here is something you may be able to use - you will have to do your own debugging, though ;-) import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;

/** * @author Sualeh Fatehi */public class SortedHashtable{

protected Hashtable hashSortedHashtable = new Hashtable(); protected Vector vectSortedHashtable = new Vector();

public Enumeration keys() {

return vectSortedHashtable.elements();

}

Page 51: Collections FAQ From jGuru

public void clear() {

hashSortedHashtable = new Hashtable(); vectSortedHashtable = new Vector();

}

public synchronized void put(String key, Entity value) {

boolean bSorted = false;

for (int i = 0; i < vectSortedHashtable.size(); i++) { Entity base = (Entity) hashSortedHashtable.get(vectSortedHashtable.elementAt(i)); if (base.compareTo(value) > 0) { vectSortedHashtable.insertElementAt(key, i); bSorted = true; break; } } if (!bSorted) { bSorted = true; vectSortedHashtable.addElement(key); } hashSortedHashtable.put(key, value);

}

protected synchronized void internalPut(String key, Entity value) {

vectSortedHashtable.addElement(key); hashSortedHashtable.put(key, value);

}

public Entity get(String key) {

return (Entity) hashSortedHashtable.get(key);

}

public synchronized void remove(String key) { vectSortedHashtable.remove(key); hashSortedHashtable.remove(key);

Page 52: Collections FAQ From jGuru

}

} // end SortedHashtable

Re: Sorted Hashtable Author: Graham Williamson (http://www.jguru.com/guru/viewbio.jsp?EID=1067855), Mar 19, 2003

If you want to maintain a sorted hashtable - either by key or object (item) then you should really extend hashtable and re-implement only the methods that you need to. Call the super methods where you need to. This way it will work with existing code that expects a hashtable. As follows...

import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;import java.lang.StringBuffer;

public class SortedKeyHashtable extends Hashtable {

private Vector keyVector = new Vector();

public Enumeration keys () { return keyVector.elements(); }//keys

public void clear () {super.clear();

keyVector = new Vector(); }//clear

public void put (String key, Vector value) { boolean bSorted = false; for (int i = 0; i < keyVector.size(); i++) { if ((Integer.parseInt(key)) > (Integer.parseInt( (String)keyVector.elementAt(i)))) { keyVector.insertElementAt(key, i); bSorted = true; break; }//i }//f if (!bSorted) { bSorted = true;

Page 53: Collections FAQ From jGuru

keyVector.addElement(key); }//i super.put(key,value); }//put public String toString () { StringBuffer strBuf = new StringBuffer(); String key = ""; for (int i = 0; i < keyVector.size(); i++) { key = (String)keyVector.elementAt(i); System.out.println(key);

strBuf.append("\n"+key+": "+super.get(key)); }//f

return strBuf.toString(); }//toString

}//SortedKeyHashtable

How do i retrieve the data from a hashmap Author: manish janjani (http://www.jguru.com/guru/viewbio.jsp?EID=1184790), Jul 8, 2004

The method that is shown is quiet confusing... can u suggest some simple method to get the values ? thnks

How can I add a Collection to another Collection?Location: http://www.jguru.com/faq/view.jsp?EID=506960 Created: Sep 29, 2001 Author: Alessandro A. Garbagnati (http://www.jguru.com/guru/viewbio.jsp?EID=32727) Question originally posed by Chris Adams (http://www.jguru.com/guru/viewbio.jsp?EID=414696

The java.util.Collection interface includes an addAll(Collection c) method to add one collection to another. Comments and alternative answers

Union of many vectors with unicite garantee Author: Ben ismail Atef (http://www.jguru.com/guru/viewbio.jsp?EID=1122692), Oct 20, 2003

In case of Vector the method addAll garantees the unicity of the added elements in the Vector. If not can you help me with an efficient source code? Thanks.

Page 54: Collections FAQ From jGuru

Where can I find performance comparisons between the different collection implementations?Location: http://www.jguru.com/faq/view.jsp?EID=507239 Created: Sep 30, 2001 Modified: 2001-09-30 15:36:34.355Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

An interresting benchmark about Java collections has been done by Bruce Eckel's in his (online) book Thinking in Java. You'll find them in Chapter 9.Comments and alternative answers

Performance benchmaks Author: Naren Varma (http://www.jguru.com/guru/viewbio.jsp?EID=750962), Feb 7, 2002You can also find performance benchmarks in the website www.precisejava.com

Performance benchmaks Author: Naren Varma (http://www.jguru.com/guru/viewbio.jsp?EID=750962), Feb 7, 2002You can also find performance benchmarks in the website www.precisejava.com

Performance benchmaks Author: Naren Varma (http://www.jguru.com/guru/viewbio.jsp?EID=750962), Feb 7, 2002

You can also find performance benchmarks in the website www.precisejava.com

How can I use two iterators to go through a collection?Location: http://www.jguru.com/faq/view.jsp?EID=507240 Created: Sep 30, 2001 Author: Nils Kulk (http://www.jguru.com/guru/viewbio.jsp?EID=337581) Question originally posed by Dohyeon KIM (http://www.jguru.com/guru/viewbio.jsp?EID=490475

Just get a separate iterator for each loop: Collection l = ...;for(Iterator i = l.iterator(); ...) { for(Iterator j = l.iterator();...) { }}

When will Java have support for type-safe collections?Location: http://www.jguru.com/faq/view.jsp?EID=507243 Created: Sep 30, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by John Zukowski PREMIUM (http://www.jguru.com/guru/viewbio.jsp?EID=7

Page 55: Collections FAQ From jGuru

It looks like JSR 14 will make it into the 1.5 releae of Java some time around 2003.

How do I traverse a map backwards?Location: http://www.jguru.com/faq/view.jsp?EID=518174 Created: Oct 11, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Dmitry Savvateev (http://www.jguru.com/guru/viewbio.jsp?EID=449458

Just keep getting the last key and the head map before it: if (!map.isEmpty()) { Object last = map.lastKey(); boolean first = true; do { if (!first) { System.out.print(", "); } System.out.print(last); last=map.headMap(last).lastKey(); first=false; } while (last != map.firstKey()); System.out.println();}(Taken from my Java Collections book.)

How do I traverse a sorted set backwards?Location: http://www.jguru.com/faq/view.jsp?EID=518176 Created: Oct 11, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Just keep getting the last element and the head set before it: if (!set.isEmpty()) { Object last = set.last(); boolean first = true; do { if (!first) { System.out.print(", "); } System.out.print(last); last=set.headSet(last).last(); first=false; } while (last != set.first()); System.out.println();}Comments and alternative answers

Alternative? Author: Troy Molander (http://www.jguru.com/guru/viewbio.jsp?EID=508870), Oct 12, 2001John,

Can you comment on the pro's and con's to this approach vs. the approach you presented:

Page 56: Collections FAQ From jGuru

List list = new LinkedList(set);Collections.reverse(list);for (Iterator it = list.iterator(); it.hasNext();){ System.out.println(it.next());}

Thanks.

repeating ".headset()" Author: zira mona (http://www.jguru.com/guru/viewbio.jsp?EID=525506), Oct 19, 2001If the implementation of the container is buggy, it can cause each head set have a pointer to its parent set, and this can lead to an almost infinite chain of references. beware.

How can I go through an Iterator mulitple times?Location: http://www.jguru.com/faq/view.jsp?EID=532217 Created: Oct 28, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7) Question originally posed by Eric Tetz (http://www.jguru.com/guru/viewbio.jsp?EID=409815

There is no direct support for this. You'll need to create your own caching mechanism. For instance, as you go through the Iterator the first time, add the elements to a LinkedList. Then, you can just get an Iterator from the LinkedList for the second pass through.

What's new to the Collections Framework in Java 1.4?Location: http://www.jguru.com/faq/view.jsp?EID=532219 Created: Oct 28, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There are three new implementations: LinkedHashSet LinkedHashMap IdentityHashMap

One marker interface: RandomAccess

And six new utility methods for the Collections class: rotate(List list, int distance) replaceAll(List list, Object oldVal, Object newVal) indexOfSubList(List source, List target) lastIndexOfSubList(List source, List target) swap(List list, int i, int j) list(Enumeration e)

How can I add an array of objects to a collection?Location: http://www.jguru.com/faq/view.jsp?EID=532232 Created: Oct 28, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

Page 57: Collections FAQ From jGuru

First you need to convert the array to a Collection. This can be done with Arrays.asList(objectArray). Once you have the array as a List, you can add it to another Collection with theCollection.addAll(theList).

Is Vector's clone method thread-safe? Location: http://www.jguru.com/faq/view.jsp?EID=538552 Created: Nov 4, 2001 Author: Bozidar Dangubic (http://www.jguru.com/guru/viewbio.jsp?EID=433955) Question originally posed by Huan Li (http://www.jguru.com/guru/viewbio.jsp?EID=524792

Sure it is, since it is a Vector which is thread-safe. Comments and alternative answers

One way to test this Author: Alex Chaffee (http://www.jguru.com/guru/viewbio.jsp?EID=3), Nov 4, 2001One way to check this is to run javap java.util.Vector

which will say, among other things, the line public synchronized java.lang.Object clone();

which more-or-less proves that the method is thread-safe.

(It doesn't -really- prove that it's thread-safe, since merely using synchronized doesn't guarantee thread safety -- the method could call a non-thread-safe shared object, for instance -- but it's a good indication.)

Where can I find an example of the Java 1.4 LinkedHashSet and LinkedHashMap classes?Location: http://www.jguru.com/faq/view.jsp?EID=568236 Created: Nov 30, 2001 Author: John Zukowski (http://www.jguru.com/guru/viewbio.jsp?EID=7)

There is an article at IBM's developerworks: Magic with Merlin: Maintaining insertion order that demonstrates their usage.

How do I load property settings with the Properties class?Location: http://www.jguru.com/faq/view.jsp?EID=581608 Created: Dec 12, 2001 Modified: 2005-08-02 18:31:05.958Author: Luigi Viggiano (http://www.jguru.com/guru/viewbio.jsp?EID=101985) Question originally posed by tyris d (http://www.jguru.com/guru/viewbio.jsp?EID=401666

java.util.Properties objects can load values from a file using the method load(InputStream).

Here is the code you need:

Properties props = new Properties();props.load(new FileInputStream("propertyfile.properties"));String value = props.getProperty("propertyname");

Page 58: Collections FAQ From jGuru

//Just a trick: in a web archive (war) you can get the InputStream inside the war archive using ClassLoader cl = this.getClass().getClassLoader();InputStream is = cl.getResourceAsStream("it/package/application.properties");

This is better than using a FileInputStream, because you are loading the file within the archive as it was a resource. You should use this.getClass().getClassLoader() to use the same ClassLoader as the one used the servlet container to load your JSP/Servlet. This code is snipped from a JSP page inside Tomcat.

How do I save properties settings with the Properties class?Location: http://www.jguru.com/faq/view.jsp?EID=705567 Created: Dec 30, 2001 Modified: 2002-02-05 10:46:16.46Author: Kenneth Tennek (http://www.jguru.com/guru/viewbio.jsp?EID=414359) Question originally posed by tyris d (http://www.jguru.com/guru/viewbio.jsp?EID=401666

Try this: Properties prop = new Properties();FileOutputStream output = new FileOutputStream("Test.properties");prop.store(output,"my testproperties");output.flush();output.close();You'll need to catch an IOException.

What happens if two threads perform a get of one hashmap at the same time? Location: http://www.jguru.com/faq/view.jsp?EID=1048741 Created: Jan 21, 2003 Author: Muruganantham Mani (http://www.jguru.com/guru/viewbio.jsp?EID=1041080) Question originally posed by Enrique Monton (http://www.jguru.com/guru/viewbio.jsp?EID=755656

[I know a HashMap object is not synchronized if not done explicitly, so in a case where you have to write and read data in a hashmap from different threads you need to synchronize it (or use another object). However in my case I am writing to the HashMap (put) only once and it is done at the beginnig. Once the HashMap is filled I am going to read it from different threads at the same time. Do I need to synchronize these reads?]

Synchronization needs to be done only when there is a chance of changing the data from different threads simultaneously. In your case, it is simply going to be a read, the synchronization is not required. If you need to remove or modify the values in the hashmap, then you [may] need to synchronize that.

For synchronizing a HashMap, you can use Collections.synchronizedMap(<your hashmap reference>) which will return a synchronized map for you, which is thread-safe.

Remember, synchronization will cause a performance problem. So, it needs to be used carefully, when really required.

Comments and alternative answers

Page 59: Collections FAQ From jGuru

very good one Author: sudhakar sadasivuni (http://www.jguru.com/guru/viewbio.jsp?EID=1101359), Jul 14, 2003This is a famous question for many of job interviews..godd one.

JDK javadoc is not lucid about it. Author: Kirill Fakhroutdinov (http://www.jguru.com/guru/viewbio.jsp?EID=501201), Aug 4, 2003Actually, JDK javadoc is not lucid about it. They said that "implementation is not synchronized" but gave as an example only structural modification.

But let's say, we have several threads trying to get objects from the same HashMap using different keys: ... hm.get("21"); ... hm.get("10"); ... hm.get("44"); at the same time.

If we are sure that get method is implemented as "atomic" operation that approach is probably OK. But let's say, that get method is implemented to first save the key we provided as a private field of HashMap internal state and then makes the search. In this case results could be unpredictable - while looking for the object with the key "21" we might get back the object corresponding to the key "44".

So to be sure that the get method returns proper value corresponding to the key we have to be sure that it is NOT modifying internal state of the shared HashMap object while searching. We can only hope for that as JDK API says nothing about it, just "implementation is not synchronized".

Re: JDK javadoc is not lucid about it. Author: Alexandru Leconiuc (http://www.jguru.com/guru/viewbio.jsp?EID=1118185), Sep 26, 2003jdk 1.4.1 javadoc for HashMap is quite clear about synchronization issues:

If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

Re[2]: JDK javadoc is not lucid about it. Author: Kirill Fakhroutdinov (http://www.jguru.com/guru/viewbio.jsp?EID=501201), Sep 26, 2003When they say "implementation is not synchronized" it usually means that all methods executed on the instance of the object potentially could be not thread-safe - whether those are getters or setters (with or without internal

Page 60: Collections FAQ From jGuru

structural modifications). For example, even access to a long or double variable is not thread-safe in Java because it could be treated nonatomic way: http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#28733

The examples/explanations that JDK is giving further could be expressed merely as: - structural modifications of HashMap are not thread-safe; - other methods including getters and setters are thread-safe but only if there are no concurrent structural modifications.

Still it is not lucid - at list for me - whether those explanations provided by JDK should be considered as examples of "implementation is not synchronized" or clarifications on how exactly "implementation is not synchronized".

How can I convert a Collection to an Array then back to a Collection?Location: http://www.jguru.com/faq/view.jsp?EID=1248289 Created: Jun 12, 2005 Modified: 2005-06-13 16:44:14.558Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The Collection interface provides a mechanism to turn a Collection into an Array using the methods <T> T[] toArray(T[] a) or Object[] toArray(). The first method will return a Array containing all the elements of the Collection with the array being that of the type provided in the method call. The second method just returns an array being of an Object[] type.

The Arrays class provides the opposite. A way to turn an array into a List using the List<T> asList(Array[] a) method. The List returned is of a fixed length with any attempts to add an element throwing an UnsupportedOperationException.

import java.util.*;

public class G{ public static void main(String[] args){ List<String> sun = new ArrayList<String>(); sun.add("Feel"); sun.add("the"); sun.add("power"); sun.add("of"); sun.add("the"); sun.add("Sun"); String[] s1 = sun.toArray(new String[0]); //Collection to array for(int i = 0; i < s1.length; ++i){ String contents = s1[i]; System.out.print(contents); } System.out.println(); List<String> sun2 = Arrays.asList(s1); //Array back to Collection for(String s2: sun2){ String s3 = s2; System.out.print(s3);

Page 61: Collections FAQ From jGuru

} //sun2.add(new String("Hello")); // throws UnsupportedOperationException } }

How can I create a Collection based on another Collection?Location: http://www.jguru.com/faq/view.jsp?EID=1250397 Created: Jun 26, 2005 Modified: 2005-06-29 19:20:06.962Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

Every concrete implementation provides a constructor, which takes a Collection as an argument. Care must be taken when creating a Collection based another Collection, this is because depending on the target concrete implementation being created, specific rules regarding duplicates may be be enforced. Such as creating a Set based on a List.

The following is a short list of the constructors provided by some of the concrete Classes of the JCF (Java Collections Framework), which enable the creation of a Collection based an another implementation.

ArrayList(Collection<? extends E> c) LinkedList(Collection<? extends E> c) Vector(Collection<? extends E> c) TreeSet(Collection<? extends E> c)

Creating a Collection based on another Collection is quite easy. The hard part is knowing which Collection to use based on performance and other issues.

For example the ArrayList created will contain the same elements in the same order as the first ArrayList created.

List<String> slist = new ArrayList<String>(); slist.add("g"); slist.add("a"); slist.add("d"); slist.add("a");slist.add("f");slist.add("e");slist.add("c");slist.add("b"); for(String s : slist){ System.out.print(s + "\t"); }System.out.println(); List<String> s2list = new ArrayList<String>(slist); for(String s : s2list){ System.out.print(s + "\t"); }When creating a Set based on an existing List the Set will be void of duplicates. List<String> slist = new ArrayList<String>(); slist.add("g"); slist.add("a"); slist.add("d");

Page 62: Collections FAQ From jGuru

slist.add("a");slist.add("f");slist.add("e");slist.add("c");slist.add("b"); for(String s : slist){ System.out.print(s + "\t"); }System.out.println(); Set<String> s2set = new TreeSet<String>(slist); for(String s : s2set){ System.out.print(s + "\t"); }

How can I define my own Comparable type so that it can be naturally sorted within a List? Location: http://www.jguru.com/faq/view.jsp?EID=1251044 Created: Jun 29, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

When taking a peek at the Java docs you will notice certain classes implement an interface named Comparable. Take a look at some of the subclasses of Number such as Byte, Integer, Long, Float or some of the classes like String and Date. What the Comparable interface provides is a way for a class to be sorted by it's natural ordering. So what do we mean by natural ordering? Depending on the type wishing to be sorted the natural ordering can be different things. If we are sorting Strings the ordering is lexicographic or alphabetic if we are sorting Dates the ordering is chronological if we are sorting Integers the ordering is numerical.

Comparable only contains one method that needs to be implemented by the class wishing to be sorted naturally. Remember if you try and sort a list that contains elements that do not implement the Comparable interface then Collections.sort() will throw an exception specifically a ClassCastException.

public interface Comparable<T>{ public int compareTo(T o); }The following is a short example on how to implement the Comparable interface and use the compareTo(T o) method. import java.util.*;

public final class Alpha implements Comparable<Alpha>{ public static void main(String[] args){ List<Alpha> alpha = new ArrayList<Alpha>(); alpha.add(new Alpha("z")); alpha.add(new Alpha("g")); alpha.add(new Alpha("k")); alpha.add(new Alpha("q")); alpha.add(new Alpha("a")); alpha.add(new Alpha("b")); alpha.add(new Alpha("o")); alpha.add(new Alpha("v")); alpha.add(new Alpha("c"));

Page 63: Collections FAQ From jGuru

Collections.sort(alpha); System.out.println(alpha); } private String letter; public Alpha(String letter){ if(letter == null){throw new NullPointerException();} this.letter = letter; } public String toString(){return letter;} public boolean equals(Alpha a){ if(!(a instanceof Alpha)) return false; return letter.equals(a.letter); } public int compareTo(Alpha a){ int i = letter.compareTo(a.letter); return i; }}More complex examples might included sorting on multiple fields. Most things that you would have to sort probably have more then one part like a name for instance (First:Middle:Last) or maybe you have to sort in (Brand:Model) order. import java.util.*;

public final class Car implements Comparable<Car>{ public static void main(String[] args){ Car[] cararry = {new Car("Toyota","Celica"), new Car("Honda","Civic"), new Car("Ford","Mustang"), new Car("Lexus","ES"), new Car("Acura","Integra"), new Car("Honda","Accord"), new Car("Acura","RL"), new Car("Toyota","Avalon") }; List<Car> car = Arrays.asList(cararry); Collections.sort(car); System.out.println(car); } private String brand; private String model; public Car(String brand, String model){ if(brand == null || model == null){throw new NullPointerException();} this.brand = brand; this.model = model; } public String toString(){return brand + " " + model;} public boolean equals(Car car){ if(!(car instanceof Car)) return false; boolean samebrand = brand.equals(car.brand); return samebrand != true ? samebrand: model.equals(car.model); } public int compareTo(Car car){ int i = brand.compareTo(car.brand); return(i != 0 ? i : model.compareTo(car.model)); }}

Page 64: Collections FAQ From jGuru

What are Generics and how can I use them?Location: http://www.jguru.com/faq/view.jsp?EID=1251440 Created: Jul 1, 2005 Modified: 2005-07-06 12:42:17.715Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

One of the biggest additions since the creation of the Collections framework is Generics.This long awaited update to the type system is a welcomed feature, which C++ developers have had in their toolbox for years using the STL. A generic type is defined using one or more type variables with it's contained methods using that type variable as a place holder to mark a parameter or return type. For instance the interface List has now been defined as.

public interface List<E>{ public add(E e); Iterator<E> iterator();} public interface Iterator<E>{ E next(); boolean hasNext();}

Type Safe Collections

So you might ask. What are Generics and why should I use them? Generics are a way to restrict a data structure to hold only a specific type thus providing compile time type checking. One of the added bonuses is that it is no longer necessary to cast a returned Object to a specific type because the compiler is aware of what type is being held by the Collection and what type is to be returned.

Set s = new SortedSet();s.add(new String("Java"));String j = (String) s.get(0); // cast required;

// java 5Set<String> s = new SortedSet<String>(); s.addElement(new String("String Type"));String s = s.get(0); // no cast required!

Having a type safe system not only obviates the need to cast to a specific type but shields the programmer against miss-casting or casting to an unrelated type at runtime.

String s = "Java, write once run anywhere"; List l = new ArrayList();l.add(new String("Java")); Integer i = (Integer)l.get(0); // Runtime exception! ClassCastException!

// Using Generics the compiler catches String s = "Java. Write once run anywhere!"; List<String> l = new ArrayList<String>();l.add(new String("Java")); Integer i = l.get(0);

Page 65: Collections FAQ From jGuru

Generics and Subtyping

Generics do not share some of the things that are commonly held true in the Java language and one of them is subtyping. One would assume the following perfectly legal since it is true that Object is a supertype of String. But the following is in fact illegal and will cause a compile time error.

List<Object> l = new ArrayList<String>();

As a rule. If X is a superclass or superinterface of Y and E is a generic type declaration then it not the case that E<X> is a supertype of E<Y>. So if E<Object> is not a super type of E<String> then what is the super type of E<String>? Read on and find out!

Wild Cards

Wild Cards represent what is called "the unknown type". Essentially they can be thought of as the supertype of any Collection. Wildcards allow some flexibility in certain situations where it is needed that a type be abstracted out. For instance what if we define the following method, printSet(Collection<Object> x). We just saw in the previous example that E<Object> is not the super type of E<String> or any other type for that matter. In this case we can change the printSet's parameter to Collection<?>. This allows us to pass in E<X> where X is any type.

public void printElements(Collection<?> c){ for(Object o: c){ System.out.println(o); }}

When working with wildcards it is always legal to read and assign the contents to an Object type

List<String> l = new ArrayList<String>();l.add(new String("Java")); Object o = getElement(l, 0); // legal

public Object getElement(List<?> l, int index){ Object o = null; try{ o = l.get(0); }catch(IndexOutOfBoundsException e){ //....... } return o; }

assigning values is another matter. The add() method takes an argument of type E which is the type that the Collection is to hold. Any type wishing to be added to the Collection would have to be of the same type. Since<?> represents an unknown type it is impossible to determine what the type parameter of the collection represents.

Bounded Wildcards

Page 66: Collections FAQ From jGuru

A Bounded Wildcard allows as type to be constrained. Bounded Wildcards are useful when there is some type of partial knowledge about the type arguments. While it is still illegal to try and add an element to a unknown Collection with a bounded type they come in handy in other situations. One use is to be able to pass not only types into a method but sub-types also. In doing this we are able to implement polymorphic behavior.

import java.util.*;

class Printer{ public void print(String s){ for(int i = 0; i < s.length(); i++){ System.out.print(s.charAt(i)); } }}class ReversePrinter extends Printer{ public void print(String s){ for(int i = s.length() - 1 ; i >= 0; i--){ System.out.print(s.charAt(i)); } }}public class G{ public static void main(String[] args){ String s = "Nothing like a good cup of Java in the morning!"; List<Printer> l = new ArrayList<Printer>(); l.add(new Printer()); printElements(l,s); List<ReversePrinter> rl = new ArrayList<ReversePrinter>(); rl.add(new ReversePrinter()); printElements(rl,s); } public static void printElements(List<? extends Printer> l, String s){ Printer printer = l.get(0); printer.print(s); System.out.println(); }}

How can I shuffle the elements of a Collection?Location: http://www.jguru.com/faq/view.jsp?EID=1253836 Created: Jul 18, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The Collections class which can be found within the java.util namespace provides two methods which suffle the elements of a Collection.

static void shuffle(List<?> list)static void shuffle(List<?> list, Random rnd) The first method shuffles the elements according to a default source of randomness, with the second using a specified source of randomness. import java.util.*;

public class ShuffleTest{

Page 67: Collections FAQ From jGuru

public static void main(String[] args){ List<String> sl = new ArrayList<String>(); sl.add("One"); sl.add("Two"); sl.add("Three"); sl.add("Four"); sl.add("Five"); sl.add("Six"); for(String s: sl){ System.out.println(s); } System.out.println(); Collections.shuffle(sl); for(String s: sl){ System.out.println(s); } }}

How can i tell if two Collections contain the same elements or have no elements in common?Location: http://www.jguru.com/faq/view.jsp?EID=1255577 Created: Jul 28, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

Two methods are needed in this case.

boolean containsAll(Collection<?> c)boolean disjoint(Collection<?>c1 Collection<?>c2)Since containsAll(Collection<?> c) is defined within the Collection interface all concrete implementations will be able to use this method. disjoint(Collection<?>c1 Collection<?>c2) is defined within the Collections class.

Using both of these methods is pretty straightforward. containsAll(Collection<?> c) is an instance method so naturally it must be invoked on an object. disjoint(Collection<?>c1 Collection<?>c2) is defined as Static within the Collections class so all that is needed is to invoke it using the class name ie Collections.disjoint(Collection<?>c1 Collection<?>c2)

How can I traverse a List backwards?Location: http://www.jguru.com/faq/view.jsp?EID=1256048 Created: Aug 1, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

In order to traverse a List backwards a ListIterator must be used. The List interface provides a method, which returns a ListIterator.

ListIterator<E> listIterator()

Using a returned ListIterator, concrete implementations of List can be traverse backwards using the following methods.

boolean hasPrevious() E previous()

Page 68: Collections FAQ From jGuru

Since ListIterator extends the Iterator interface forward direction is still possible via Iterators methods. boolean hasNext()E next() import java.util.List; import java.util.ArrayList; import java.util.ListIterator;

public class { public static void main(String[] args){ List<String> slist = new ArrayList<String>(); slist.add("1"); slist.add("2"); slist.add("3"); slist.add("4"); ListIterator i = slist.listIterator(); while(i.hasNext()){ System.out.print(i.next()); } System.out.println(); while(i.hasPrevious()){ System.out.print(i.previous()); } }}Comments and alternative answers

Starting at the end Author: Brad Rust (http://www.jguru.com/guru/viewbio.jsp?EID=1259080), Aug 22, 2005You can start at the end of the list with a ListIterator li = list.listIterator(list.size()) There are lots of examples on the next which iterate down the list and then back up. You may not want that functionality.

How can I get a sorted list of keys that are contained within a Map?Location: http://www.jguru.com/faq/view.jsp?EID=1256541 Created: Aug 3, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The Map interface defines a method named keySet() which concrete classes such as HashMap and TreeMap implement. Depending on the implementation on which keySet() is invoked the returned Set might not contain it's elements (keys) in sorted order. For instance the HashMap class makes no guarantees as to the order of the elements contained within. Whereas the TreeMap class does guarantee element ordering since it implements the SortedMap interface.

/* TreeMap used. Keys stored in ascending order */

Map<String,String> book = new TreeMap<String,String>(); book.put(new String("Java"),new String("A trademark used for a programming language designed to develop applications, especially ones for the Internet, that can operate on different platforms."));

Page 69: Collections FAQ From jGuru

book.put(new String("C#"),new String("An object-oriented language devised and promoted by Microsoft, intended to replace Java, which it strongly resembles."));book.put(new String("Python"),new String("A simple, high-level interpreted language by Guido van Rossum"));book.put(new String("LISP"),new String("A programming language designed to process data consisting of lists. It is widely used in artificial intelligence research.")); Set words = book.keySet();for(Iterator i = words.iterator();i.hasNext();){ System.out.print(i.next() + "\t");}Comments and alternative answers

getting sorted list of keys from a map Author: sandeep sharma (http://www.jguru.com/guru/viewbio.jsp?EID=1261951), Sep 12, 2005Create a TreeMap from the given map. Map maptree = new TreeMap(map);Iterator it = maptree.keySet().iterator();while(it.hasNext()){ String st = it.next().toString(); System.out.println(st);}If ur keys r not primitive type then u need to implement comparable interface or use comparator and overrride compareto() method which is used while sorting.

How can I create a read only Collection?Location: http://www.jguru.com/faq/view.jsp?EID=1258089 Created: Aug 15, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException.

Collection<T> unmodifiableCollection(Collection<? extends T> c)List<T> unmodifiableList(List<? extends T> list) Set<T> unmodifiableSet(Set<? extends T> s)SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) import java.util.*;

public class Unmod{ public static void main(String[] args){ List<String> strlist = new ArrayList<String>(); strlist.add("C"); strlist.add("B"); strlist.add("A"); Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist); // unmodstrlist.add("G"); throws UnsupportedOperationException

Page 70: Collections FAQ From jGuru

Set<String> strset = new TreeSet<String>(); strset.add("C"); strset.add("B"); strset.add("A"); Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset); // unmodstrset.add("G"); throws UnsupportedOperationException } public static Collection<String> makeUnmodifiable(Collection<String> c){ return(Collections.unmodifiableCollection(c)); }}

Is there a way determine how many times an Object occurs within a Collection?Location: http://www.jguru.com/faq/view.jsp?EID=1258262 Created: Aug 16, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The Collections class provides a method which returns the number of times an Object appears within a given Collection.

public static int frequency(Collection<?> c, Object o)If a null Collection is passed in then a NullPointerException is thrown. import java.util.*;

public class Freq { public static void main(String[] args){ List<Integer> password = new ArrayList<Integer>(); password.add(new Integer(4)); password.add(new Integer(6)); password.add(new Integer(8)); password.add(new Integer(4)); password.add(new Integer(9)); Integer passwordelement = new Integer(4); System.out.println(passwordelement + " appears " + getFrequency(password,passwordelement) + " times within password"); } private static int getFrequency(Collection c, Object o){ return(Collections.frequency(c,o)); }}

What is the easiest way to obtain a Map Entry?Location: http://www.jguru.com/faq/view.jsp?EID=1260600 Created: Sep 1, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

The easiest way to obtain a Map Entry or (key-value pair) is by invoking the following method provided by the Map interface.

Set<Map.Entry<K,V>> entrySet();

Page 71: Collections FAQ From jGuru

The entrySet() method returns a Set which is populated with Map.Entry objects. The only way to obtain a reference to a Map.Entry is by using an Iterator on the returned Set view. Once a reference to a Map.Entry is obtained the follow methods can be invoked which return the key and value corresponding to the entry.

K getKey()V getValue()import java.util.Map; import java.util.Set;import java.util.TreeMap; import java.util.Iterator;

public class Emps{ public static void main(String[] args){ Map<String,String> empmap = new TreeMap<String,String>(); empmap.put("956544","Bob Jones"); empmap.put("132485","Phil Harris"); empmap.put("102161","Kamal Uganda"); empmap.put("226545","Bill Russel"); empmap.put("116423","Dorris Smith"); Set s = empmap.entrySet(); for(Iterator i = s.iterator();i.hasNext();){ Map.Entry me = (Map.Entry)i.next(); System.out.println(me.getKey() + " : " + me.getValue()); } }}Comments and alternative answers

Fully generified version Author: Hans-Peter Schmid (http://www.jguru.com/guru/viewbio.jsp?EID=1070432), Sep 11, 2005

Here is the fully "generified" version of the code (the only changes are in the loop at the end). Note that you could use an explicit iterator, but unless you want to call remove on the iterator, the new for loop syntax seems preferable for its brevity.

import java.util.Map; import java.util.Set;import java.util.TreeMap; import java.util.Iterator;

public class Emps{ public static void main(String[] args){ Map<String,String> empmap = new TreeMap<String,String>(); empmap.put("956544","Bob Jones"); empmap.put("132485","Phil Harris"); empmap.put("102161","Kamal Uganda"); empmap.put("226545","Bill Russel"); empmap.put("116423","Dorris Smith");

for (Map.Entry<String,String> entry: empmap.entrySet()){

Page 72: Collections FAQ From jGuru

System.out.println( entry.getKey() + " : " + entry.getValue()); } }}

Re: Fully generified version Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666), Sep 12, 2005Pretty cool Peter! Thanks for the update.

How can I find the maximum element contained within a Collection?Location: http://www.jguru.com/faq/view.jsp?EID=1261604 Created: Sep 8, 2005 Author: Brandon Rohlfs (http://www.jguru.com/guru/viewbio.jsp?EID=1245666)

Finding the maximum element within a Collection is easy. The following method can be used which can be found within the Collections class.

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)This method returns the maximum element of the given Collection according to the natural ordering of it's elements. This means that all elements must implement the Comparable interface. With the following code below the implementation of the Comparable interface is already taken care of since the class Byte already implements this interface. import java.util.Set;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;

public class Max{ public static void main(String[] args){ Collection<Byte> numl = new ArrayList<Byte>(); numl.add(new Byte("2")); numl.add(new Byte("6")); numl.add(new Byte("3")); numl.add(new Byte("1")); numl.add(new Byte("5")); numl.add(new Byte("4")); System.out.print("Max element is " + getMax(numl)); } public static Byte getMax(Collection<Byte> c){ return Collections.max(c); }}

If the element type being store within the Collection is user defined, implementation of the Comparable interface must be provided.

import java.util.Set;import java.util.ArrayList;

Page 73: Collections FAQ From jGuru

import java.util.Collection;import java.util.Collections;

public class Max{ public static void main(String[] args){ Collection<Num> numl = new ArrayList<Num>(); numl.add(new Num("2")); numl.add(new Num("6")); numl.add(new Num("3")); numl.add(new Num("1")); numl.add(new Num("5")); numl.add(new Num("4")); System.out.print("Max element is " + getMax(numl).getNum()); } public static Num getMax(Collection<Num> c){ return Collections.max(c); }}class Num implements Comparable<Num>{ private String i; public Num(String i){ this.i = i; } public int compareTo(Num num){ int x = i.compareTo(num.i); return x; } public String getNum(){ return i; }}