Section 11.3. Collections Overview

   

11.3 Collections Overview

Collections represent a group of related objects. The objects may or may not be ordered. The SDK does not offer a direct implementation of this interface; the interface is implemented using one of the subinterfaces.

Collections have changed significantly over the years . Just as the way that Java handles user interface events and graphics has changed so much between AWT and Swing, collections have seen significant changes and additions. There are far more kinds of collections than there were in Java 1.0 ”at that time there were a total of four. Now in Java 1.4 there are closer to 20.

The original collections are important to discuss briefly for two reasons. First, you will see a lot of code implementing these collections. Some are still central to application development, and some have been usurped by more efficient collections developed since. The second reason is that, just as with ColdFusion structures, Java uses them internally within the compiler and the runtime system.

Here are the four original collections:

  • Enumeration is an interface that specifies what methods to implement when iterating over a set of related references. Enumeration objects are useful to move through a set of elements one at a time.

  • Hashtable is a class that allows you to store and retrieve object references from a collection using keys. This has perhaps the most in common with ColdFusion structures. The Hashtable is nearly identical to the newer Hashmap , but Hashtable 's methods are synchronized .

  • Stack is a class that stores object references that are accessed in LIFO (last in, first out) style.

  • Vector is a class that stores arrays of object references. An advantage to using a Vector is that its internal array can be expanded to accommodate more data if necessary. Vector s are also synchronized and incur a good deal of overhead in their use. While commonly found in legacy code, Vector s are declining in popularity, given the overhead and many alternatives.

We will elaborate on these collections and the other collection types they begot in the remainder of this chapter.

11.3.1 Properties

Since the JDK 1.0 we have also had access to an object holding system properties via the properties class. Properties is a subclass of java.util.Hashtable , which is derived from the obsolete java.util.Dictionary class. Properties can be saved to a stream or loaded from a stream, and each property value is accessible as a string. The information stored in the system properties set details Java settings, all of which are available to regular applications, but only a few of which are available to applets (for security reasons).

Listing Props.java demonstrates how to access system properties, which you can use in your programs to base settings on.

11.3.2 Props.java

 /*   * File: Props.java  * Purpose: displays system properties  */ package chp11; import java.util.Properties; import java.util.Enumeration; public class Props {     public static void main (String [] a) {             // get a properties object         Properties p = System.getProperties();             // returns an enumeration object             // which can be iterated over         Enumeration e = p.propertyNames();         while (e.hasMoreElements()) {             String key = (String) e.nextElement();             String value = p.getProperty(key);             System.out.println(key + ": " + value);         }     } } 

The output when run is as below. Your output will vary based on your settings:

 C:\jdk1.4\bin\javaw.exe                              -classpath C:\jdk1.4\jre\lib\rt.jar;C:\jdk1.4\jre\lib\ext\dnsns.jar;C:\jdk 1.4\jre\lib\ext\ldapsec.jar;C:\jdk1.4\jre\lib\ext\localedata. jar;C:\jdk1.4\jre\lib\ext\sunjce_provider.jar;C:\IntelliJ_IDEA\ JavaForCF chp11.Props  java.runtime.name: Java(TM) 2 Runtime Environment, Standard Edition sun.boot.library.path: C:\jdk1.4\jre\bin java.vm.version: 1.4.0-b92 java.vm.vendor: Sun Microsystems Inc. java.vendor.url: http://java.sun.com/ path.separator: ; java.vm.name: Java HotSpot(TM) Client VM file.encoding.pkg: sun.io user.country: US sun.os.patch.level: java.vm.specification.name: Java Virtual Machine Specification user.dir: C:\IntelliJ_IDEA java.runtime.version: 1.4.0-b92 java.awt.graphicsenv: sun.awt.Win32GraphicsEnvironment java.endorsed.dirs: C:\jdk1.4\jre\lib\endorsed os.arch: x86 java.io.tmpdir: C:\DOCUME~1\eben\LOCALS~1\Temp\ line.separator: java.vm.specification.vendor: Sun Microsystems Inc. user.variant: os.name: Windows XP sun.java2d.fontpath: java.library.path: C:\jdk1.4\bin;.;C:\WINDOWS\System32;C:\WINDOWS;C:\jdk1.4\bin;C: \WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\jdk1.4 \bin; java.specification.name: Java Platform API Specification java.class.version: 48.0 java.util.prefs.PreferencesFactory: java.util.prefs.WindowsPreferencesFactory os.version: 5.1 user.home: C:\Documents and Settings\eben user.timezone: java.awt.printerjob: sun.awt.windows.WPrinterJob file.encoding: Cp1252 java.specification.version: 1.4 user.name: eben java.class.path: C:\jdk1.4\jre\lib\rt.jar;C:\jdk1.4\jre\lib\ext\dnsns.jar;C:\jdk 1.4\jre\lib\ext\ldapsec.jar;C:\jdk1.4\jre\lib\ext\localedata. jar;C:\jdk1.4\jre\lib\ext\sunjce_provider.jar;C:\IntelliJ_IDEA\ JavaForCF java.vm.specification.version: 1.0 sun.arch.data.model: 32 java.home: C:\jdk1.4\jre java.specification.vendor: Sun Microsystems Inc. user.language: en awt.toolkit: sun.awt.windows.WToolkit java.vm.info: mixed mode java.version: 1.4.0 java.ext.dirs: C:\jdk1.4\jre\lib\ext sun.boot.class.path: C:\jdk1.4\jre\lib\rt.jar;C:\jdk1.4\jre\lib\i18n.jar;C:\jdk1.4\ jre\lib\sunrsasign.jar;C:\jdk1.4\jre\lib\jsse.jar;C:\jdk1.4\jre\ lib\jce.jar;C:\jdk1.4\jre\lib\charsets.jar;C:\jdk1.4\jre\classes java.vendor: Sun Microsystems Inc. file.separator: \ java.vendor.url.bug: http://java.sun.com/cgi-bin/bugreport.cgi sun.cpu.endian: little sun.io.unicode.encoding: UnicodeLittle sun.cpu.isalist: pentium i486 i386 Process terminated with exit code 0 

What the above code provides for you is a way to, for instance, create a more flexible program that uses variables for system-dependent properties. This could help ease cross-platform support and can be useful in cases where you develop on, say, Windows, and deploy to a Linux server. For example, different file systems use different characters for file path separators; Linux uses a / while Windows uses a \ . So instead of calling files with these items hardcoded, you could use the file.separator property instead:

 p.getProperty("file.separator"); 

Properties is a subclass of the Hashtable collection and is an ideal choice for storing configuration files. Developers have often used it for user preferences as well. In JDK 1.4, the API includes a preferences object, available as java.util.prefs.Preferences , to act as a front end for persistent data stores.

Note

Note that the properties object maintains strings in key-value pairs much like a ColdFusion structure.


The following example shows a way to interact with the properties as you might define them in a program.

11.3.3 AppProps.java

 package chp11;  import java.util.*; import java.io.*; public class AppProps {     public static void main(String [] a) {         // get the user home directory property     String dir = System.getProperty("user.home");     Properties useroptions = new Properties();         // make a new file in the user.home directory         // on my Win XP machine this is         // C:\Documents and Settings\eben\     File configfile = new File(dir +      System.getProperty("file.separator") +  "AppProps.conf");     try {             // get an input stream         useroptions.load(new FileInputStream(configfile));     }     catch (IOException ie) {         System.out.println(ie.getMessage());     }            // set some properties      useroptions.setProperty("favoriteColor","blue");      useroptions.setProperty("preferredFont","Verdana");    try {             // output stream to send file data             // add a comment to the top of the file        useroptions.store(new FileOutputStream(configfile), "AppProperties");        System.out.println("Your favorite color is: " +                useroptions.getProperty("favoriteColor"));    }     catch (IOException e) {         System.out.println(e.getMessage());     }     } } 

This program generates this output to the console:

 Your favorite color is: blue 

More importantly, if you navigate to your user.home directory, you should find a file there called AppProps.conf . Open it in a text editor, and you should see output similar to the following:

 #AppProperties  #Sun Jun 23 18:53:07 GMT-07:00 2002 favoriteColor=blue preferredFont=Verdana 

If this file did not exist already, Java created it for you. Notice that you can modify the file to set another property, and that it will not overwrite or harm any other properties that may be set in the file; it will just append them to the properties list. Properties are surprisingly useful and easy to use.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net