<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:series="http://unfoldingneurons.com/"
	>

<channel>
	<title>Cyberward.net &#187; Tutorial</title>
	<atom:link href="http://www.cyberward.net/blog/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cyberward.net/blog</link>
	<description>The Drive Failures and Shutter Clicks of Christopher Ward</description>
	<lastBuildDate>Wed, 21 Jul 2010 12:00:15 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating LVM Virtual Drives</title>
		<link>http://www.cyberward.net/blog/2009/06/creating-lvm-virtual-drives/</link>
		<comments>http://www.cyberward.net/blog/2009/06/creating-lvm-virtual-drives/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 12:00:50 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Hardware]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Building a NAS]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[lvm]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1361</guid>
		<description><![CDATA[
Now that we have a raid array created, we are going to create some virtual drives. Why virtual drives? Well, we have one large terabyte drive right now, and if we just put folders in there, it can quickly get cumbersome. You have no control on size of those folders, and permissions can be more [...]]]></description>
			<content:encoded><![CDATA[<p><img class="size-full wp-image-1362 alignnone" title="driveicons" src="http://www.cyberward.net/blog/wp-content/uploads/driveicons.png" alt="driveicons" width="430" height="112" /></p>
<p>Now that we have a raid array created, we are going to create some virtual drives. Why virtual drives? Well, we have one large terabyte drive right now, and if we just put folders in there, it can quickly get cumbersome. You have no control on size of those folders, and permissions can be more difficult. And if you try to share this drive, you can&#8217;t assign different drive letters in windows to different folders, just one to the drive. One other issue is file system. I am going to use just a basic file system here, but in the past I have created different file systems based on the type of use ie. large video files, small text files, etc. Making those decisions is beyond the scope of this tutorial, and I have decided that for my purposes now, it doesn&#8217;t matter that much. You can decided differently.</p>
<p>What we will discuss is using LVM. This enables you to set up virtual drives that can contain different file systems, and that can be grown and shrunk (usually) to fit the space needs of the system. We will look at maintenance of these file systems at a later tutorial. Here we will create a backup, and a pictures virtual drive. We will not use the full terabyte of space, so that we can grow these as needed, or add another for say music at another time.</p>
<p>I will once again be doing this on an ubuntu system, but the use of these tools is fairly standard across linux distributions.<br />
<span id="more-1361"></span><br />
First we will need to make sure that you have LVM installed.</p>
<pre class="linux">sudo apt-get install lvm2</pre>
<p>We need to create what is called a physical volume. We need to tell LVM what actual physical drives are involved. Lets check what drives we have again.</p>
<pre class="linux">$ sudo fdisk -l

Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1               1      121601   976760001   fd  Linux raid autodetect

Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes
255 heads, 63 sectors/track, 121601 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0xfe76bc93

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1      121601   976760001   fd  Linux raid autodetect</pre>
<p>This is just a partial list of the drives. See that the /dev/sda1 and /dev/sdb1 drives have a system type of fd. In the last part of teh tutorial we set up software raid. If you are NOT using raid, you will need to add these devices to your physical volume. For us, we are going to add /dev/md0 that we created last time. Lets just verify that the array is there.</p>
<pre class="linux">$ sudo mdadm --detail --scan
ARRAY /dev/md0 level=raid1 num-devices=2 metadata=00.90 UUID=****</pre>
<p><em>Note: all UUID&#8217;s will be replaced with **** in this doc. They will be different on every machine anyway.</em></p>
<p>As you can see, array /dev/md0 is ready to go. Lets create that physical volume finally.</p>
<pre class="linux">sudo pvcreate /dev/md0</pre>
<p>You can verify that it is created with the pvdisplay command.</p>
<pre class="linux">$ sudo pvdisplay
  "/dev/md0" is a new physical volume of "931.51 GB"
  --- NEW Physical volume ---
  PV Name               /dev/md0
  VG Name
  PV Size               931.51 GB
  Allocatable           NO
  PE Size (KByte)       0
  Total PE              0
  Free PE               0
  Allocated PE          0
  PV UUID               ****</pre>
<p>Now we need to create our volume group. That last step identified what hardware LVM has available. This next step groups that hardware into volume groups. I will call my &#8220;nas&#8221;.</p>
<pre class="linux">sudo vgcreate nas /dev/md0</pre>
<p>We can then verify our volume group.</p>
<pre class="linux">$ sudo vgdisplay
  --- Volume group ---
  VG Name               nas
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  1
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                0
  Open LV               0
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               931.51 GB
  PE Size               4.00 MB
  Total PE              238466
  Alloc PE / Size       0 / 0
  Free  PE / Size       238466 / 931.51 GB
  VG UUID               ****</pre>
<p>Next, we can finally create our virtual drives. I am going to create a backup drive of 100 gig, and a pictures drive of 400 gig, both which are added to the &#8220;nas&#8221; volume group. You can create drives of what ever size you would like.</p>
<pre class="linux">sudo lvcreate --name backup --size 100G nas
sudo lvcreate --name pictures --size 400G nas</pre>
<p>You can see information about these virtual drives with another display command. Guess what it is.</p>
<pre class="linux">$ sudo lvdisplay
  --- Logical volume ---
  LV Name                /dev/nas/backup
  VG Name                nas
  LV UUID                gqrIVE-YtS4-cBne-QyPK-oMO1-7V7V-UaBoUL
  LV Write Access        read/write
  LV Status              available
  # open                 0
  LV Size                100.00 GB
  Current LE             25600
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           254:0

  --- Logical volume ---
  LV Name                /dev/nas/pictures
  VG Name                nas
  LV UUID                oDxJJi-lxsG-9RHw-RBME-oJah-jOJJ-J8I4p3
  LV Write Access        read/write
  LV Status              available
  # open                 0
  LV Size                400.00 GB
  Current LE             102400
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           254:1</pre>
<p>Now that we have our virtual drives, can we start filling them up? Not quite. We need partitions on them. These drives are just like a bare drive from the factory. We can put whatever file system we want on them. I am just going to use ext3. This may not be the best file system out there, but it is proven, and works good enough for me.</p>
<pre class="linux">sudo mkfs.ext3 /dev/nas/backup
sudo mkfs.ext3 /dev/nas/pictures</pre>
<p>That takes a little bit of time, just as would without LVM. As far as your programs, and bash, and Gnome are concerned, /dev/nas/backup is just another drive. It does not care, and does no know that underneath all this is a raid array and virtual drives.</p>
<p>Now we need to get them mounted so that they are useable. First off, I create a couple of mount points. I like to keep them organized.</p>
<pre class="linux">sudo mkdir /var/nas
sudo mkdir /var/nas/backup /var/nas/pictures

sudo mount /dev/nas/backup /var/nas/backup
sudo mount /dev/nas/pictures /var/nas/pictures</pre>
<p>Now, do a &#8220;df&#8221; to see the drives on the system and the space used.</p>
<pre class="linux">$ df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sdd1            186693520   2469660 174740292   2% /
/dev/mapper/nas-backup
                     103212320    192248  97777192   1% /var/nas/backup
/dev/mapper/nas-pictures
                     412849328    203156 391674652   1% /var/nas/pictures</pre>
<p><em>Note: I removed other system file systems that we are not talking about here.</em></p>
<p>You can see that our two drives are there. They are listed at /var/mapper/nas-backup and /var/mapper/nas-pictures, but they are the /dev/nas/backup and /dev/nas/pictures we have been setting up.</p>
<p>Now you can copy your data into these drives.</p>
<p>I am not the only one that uses these drives, and they will be shared on samba (later tutorial) so I like to change the permissions on these folders. I will create a &#8220;nas&#8221; group, add myself (insert your user id for *user*), and change the permissions.</p>
<pre class="linux">sudo groupadd nas
sudo adduser *user* nas
sudo chown -R *user*:nas /var/nas/backup
sudo chown -R *user*:nas /var/nas/pictures</pre>
<p>The file permissions are set up as writable by owner and readable by group and other. I will leave them this way for now.</p>
<p>Things look good to go, and they would for awhile, until you reboot. Then your drives would disappear. We need to make them a little more permanent. We do this by putting some entries in the /etc/fstab file. This is the list of all mountable file systems that the OS uses to connect things up when booting.</p>
<p>This file in Ubuntu is using UUID&#8217;s, so we will to. First thing you need to do is find out what yours are. So&#8230;</p>
<pre class="linux">
$ sudo blkid
/dev/sdc1: UUID="****1" SEC_TYPE="ext2" TYPE="ext3"
/dev/sdd1: UUID="****2" TYPE="ext3"
/dev/sdd5: TYPE="swap" UUID="****3"
/dev/sda1: UUID="****4" TYPE="mdraid"
/dev/sdb1: UUID="****5" TYPE="mdraid"
/dev/md0: UUID="****6" TYPE="lvm2pv"
/dev/mapper/nas-backup: UUID="****7" TYPE="ext3"
/dev/mapper/nas-pictures: UUID="****8" TYPE="ext3"
</pre>
<p>You can see the unique ID&#8217;s that are assigned to the drives in the array, the raid array its self, the LVM physical volume, and finally, the two logical volumes. Use these UUID&#8217;s that you get when you execute blkid. Now lets edit /etc/fstab</p>
<pre class="linux">
$ sudo nano -w /etc/fstab
# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>       <dump>
<pass>
proc            /proc           proc    defaults        0       0
# /dev/sdd1
UUID=****2 /               ext3    relatime,errors=remount-ro 0  $
# /dev/sdd5
UUID=****3 none            swap    sw              0       0
/dev/scd0       /media/cdrom0   udf,iso9660 user,noauto,exec,utf8 0       0

#/dev/nas/backup
UUID=****7 /var/nas/backup ext3    relatime,noexec 0 2

#/dev/nas/pictures
UUID=****8 /var/nas/pictures ext3  relatime,noexec 0 2
</pre>
<p>You shouldn&#8217;t have to change anything except add the lines at the bottom for the backup and pictures drives (or whatever you created) . Please use the UUID&#8217;s you found from blkid.</p>
<p>Press ctrl-x to exit nano and save the file. </p>
<p>Try a reboot and see how it works. Once you bring the system back up, open a terminal and type df. This will show you all mounted drives, and your new drives should be there.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/creating-lvm-virtual-drives/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intro to Java Observer Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-observer-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-observer-pattern/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 16:27:07 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[observer]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1312</guid>
		<description><![CDATA[We are well into this whole patterns thing now, picking up lots of new lingo, and becoming better at communicating with other developers. Next on the list: the observer pattern. This is an important pattern to use to help prevent tight coupling and keep code separated into discrete objects. This pattern allows communication between two [...]]]></description>
			<content:encoded><![CDATA[<p>We are well into this whole patterns thing now, picking up lots of new lingo, and becoming better at communicating with other developers. Next on the list: the observer pattern. This is an important pattern to use to help prevent tight coupling and keep code separated into discrete objects. This pattern allows communication between two objects at particular times without each object needing to be too tightly coupled to the other.</p>
<h3>The Observer in the Physical World</h3>
<p>The idea behind the observer is like a subscription. Do you have a newspaper or magazine subscription? Have you signed up for cell phone texts from your favorite band when they have new tour dates? The act of you signing up with the newspaper, the magazine, or the band, is you saying you want a subscription, or that you want to become an observer. When the subject (newspaper, magazine, band) has something new to share (on a schedule or not) they run down their subscriber list, and notify the observers by mail, or text.</p>
<h3>The Observer in the Software World</h3>
<p>On the software side, the idea is the same. Your subject needs to provide a way to take subscriptions, hold a list of observers, and when a particular state changes, notify them. There is usually a couple of methods on the subject that takes in an interface that is used for getting on or off the subscription list. On this interface is also the &#8220;call back&#8221; method. This is the method that the subject will execute when it wants to inform the observers of state changes.<br />
<span id="more-1312"></span></p>
<h3>Do you have a picture?</h3>
<p><a href="http://www.cyberward.net/blog/wp-content/uploads/observercld.jpg"><img class="aligncenter wp-image-1313" title="observer pattern" src="http://www.cyberward.net/blog/wp-content/uploads/observercld.jpg" alt="observer pattern" width="500" height="241" /></a>¬†</p>
<p>Here is a class diagram for our first example. We have two classes and an interface. The interface, NumberObserver is the piece that connects the subject and the observer together. The NumberHolder class has methods to add and remove our observer from an internal list. The NumberDisplayer sets this object and the notify method on NumberHolder. The way it was implemented here was that NumberDisplayer implemented the interface. This is not the only way to do it. NumberDisplayer could create an inner class, or there could be an external class that implements the NumberObserver interface. It doesn&#8217;t matter. All that does matter is that NumberDisplayer passes a NumberObserver object to NumberHolder that implements the notifyNewNumber method. When NumberHolder changes it&#8217;s number, it then notifies all the observers by looping over the list it has of observers and executing the notifyNewNumber method on each one.</p>
<p>The NumberObserver is very basic. Just one method is defined here. The value that will be sent by the subject is the new number.</p>
<pre lang="java" name="NumberObserver.java" colla="+">
public interface NumberObserver {
   public void notifyNewNumber(int pNewValue);
   }
}
</pre>
<p>The NumberHolder doesn&#8217;t have much going on either. Most of the code is just to take care of the observers. Note the add, remove, and update observer methods.</p>
<pre lang="java" name="NumberHolder.java" colla="+">
public class NumberHolder {
   private int number;
   private List<NumberObserver> observerList;

   public NumberHolder() {
      number = 10;
      observerList = new ArrayList<NumberObserver>();
   }

   public void setNumber(int pNumber) {
      System.out.println("Number set to " + pNumber);
      number = pNumber;
      updateObservers();
   }

   public void addObserver(NumberObserver pObserver) {
      System.out.println("Adding observer:" + pObserver);
      observerList.add(pObserver);
   }

   public void removeObserver(NumberObserver pObserver) {
      System.out.println("Removing observer:" + pObserver);
      observerList.remove(pObserver);
   }

   private void updateObservers() {
      for (NumberObserver aObserver : observerList) {
         aObserver.notifyNewNumber(number);
      }
   }
}
</pre>
<p>And finally, the NumberDisplayer class that implements the NumberObserver interface.</p>
<pre lang="java" name="NumberDisplayer.java" colla="+">
public class NumberDisplayer implements NumberObserver {
   private String name;

   public NumberDisplayer(String pName) {
      name = pName;
   }

   public void notifyNewNumber(int pNewValue) {
      System.out.println(name + " is now displaying " + pNewValue);
   }
}
</pre>
<p>NumberHolderTest puts these three classes together. It creates several NumberDisplayer classes and adds and removes objects from the NumberHolder as well as updating the value. Run this to see the observer at work.</p>
<pre lang="Java" name="NumberHolderTest.java" colla="-">
public class NumberHolderTest {
   public static void main(String[] args) {
      NumberHolder aNumberHolder = new NumberHolder();

      // we can set the number at any time. Nothing happens because we don't
      // have any observers registered.
      aNumberHolder.setNumber(10);

      // Each NumberDisplayer will register with the NumberHolder
      NumberDisplayer aObserverAndDisplayerOne = new NumberDisplayer("One");
      aNumberHolder.addObserver(aObserverAndDisplayerOne);

      NumberDisplayer aObserverAndDisplayerTwo = new NumberDisplayer("Two");
      aNumberHolder.addObserver(aObserverAndDisplayerTwo);

      NumberDisplayer aObserverAndDisplayerThree = new NumberDisplayer("Three");
      aNumberHolder.addObserver(aObserverAndDisplayerThree);

      // Each NumberDisplayer should get notified of the change
      aNumberHolder.setNumber(20);

      // Remove two observers
      aNumberHolder.removeObserver(aObserverAndDisplayerOne);
      aNumberHolder.removeObserver(aObserverAndDisplayerTwo);

      // Now only one observer is left
      aNumberHolder.setNumber(30);
   }
}
</pre>
<p>The main idea here is that we can keep the two objects loosely coupled, with the one interface joining them together. The way this is done can vary a bit. In this particular case we have chosen to pass the new number. You could pass a different interface that exposed methods on the subject. You could just have a method that doesn&#8217;t pass anything if just need to know that something happened.</p>
<p>Let&#8217;s look at another example, this time using our Animal classes.</p>
<h3>Defining the problem</h3>
<p>We have a zoo. A zoo contains many cages, each cage contains several animals. The zoo keepers would like to have an up-to-date tally of all the animals in the zoo. Every time animals are added or removed from the cages, they want to know the totals. Let&#8217;s look at this without the observer pattern first.</p>
<h3>No Observer Pattern</h3>
<pre lang="Java" name="Cage1.java" colla="-">
public class Cage1<T extends Animal> {

   // List to hold our animals
   private List<T> animalList;

   public Cage1() {
      animalList = new ArrayList<T>();
   }

   public void insertAnimal(T pAnimal) {
      animalList.add(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is added to the cage.");
   }

   public void removeAnimal(T pAnimal) {
      animalList.remove(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is removed from the cage.");
   }

   public void clearCage() {
      animalList.clear();
   }

   public List<T> getAnimals() {
      return animalList;
   }
}
</pre>
<pre lang="Java" name="Zoo1.java" colla="-">
public class Zoo1 {
   private List<Cage1<? extends Animal>> cages;

   public Zoo1() {
      cages = new ArrayList<Cage1<? extends Animal>>();
   }

   public void addCage(Cage1<? extends Animal> pCage) {
      cages.add(pCage);
   }

   public void removeCage(Cage1<? extends Animal> pCage) {
      cages.remove(pCage);
   }

   public void doCageUpdated() {
      Map<String, Integer> aAnimalCounts = getAnimalCounts();
      displayAnimalCounts(aAnimalCounts);
   }

   public Map<String, Integer> getAnimalCounts() {
      Map<String, Integer> aAnimalCounts = new HashMap<String, Integer>();
      for (Cage1<? extends Animal> aCage : cages) {
         List<? extends Animal> aAnimalList = aCage.getAnimals();
         int aCount = aAnimalList.size();
         if (aCount > 0) {
            String aType = aAnimalList.get(0).getType();
            Integer aTypeCount = aAnimalCounts.get(aType);
            if (aTypeCount == null) {
               aTypeCount = new Integer(aCount);
            } else {
               aTypeCount = new Integer(aTypeCount.intValue() + aCount);
            }
            aAnimalCounts.put(aType, aTypeCount);
         }
      }
      return aAnimalCounts;
}

   public void displayAnimalCounts(Map<String, Integer> animalCounts) {

      Set<String> aAnimalSet = animalCounts.keySet();
      if (aAnimalSet == null || aAnimalSet.isEmpty()) {
         System.out.println("\nZoo is currently empty.");
      } else {
         System.out.println("\nCurrent zoo animal counts:");
      }
      for (String aType : aAnimalSet) {
         Integer aTypeCount = animalCounts.get(aType);
         System.out.println("There are " + aTypeCount.intValue() + " of type " + aType);
      }
   }
}
</pre>
<p>See Cage1.java. Pretty simple. Just a simple list, and the methods to support getting data in and out of the list. Now look at Zoo1.java. This class contains the cages in a List. It also has the methods that can look at all the cages and create the totals for each animal type.</p>
<p>There is also a method doCageUpdated that must be called everytime an animal is added to a cage. The way we have this set up so far, there is no way for the zoo to know when an animal is added to a cage. A cage knows where an animal is added, but the cage doesn&#8217;t know about the zoo. It is contained within the zoo, but there is no coupling between the cage, and the zoo. We could insert a reverence for the zoo into the cage when the cages are added to the zoo, but we try to avoid this circular coupling.</p>
<pre lang="Java" name="ZooTest1.java" colla="-">
public class ZooTest1 {
   public static void main(String[] args) {

      Zoo1 aZoo = new Zoo1();

      Cage1<Bird> aBirdCage = new Cage1<Bird>();
      aZoo.addCage(aBirdCage);

      aBirdCage.insertAnimal(new Bird());
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aBirdCage.insertAnimal(new Bird());
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      Cage1<Mammal> aMammalCage = new Cage1<Mammal>();
      aZoo.addCage(aMammalCage);
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      Mammal aFred = new Mammal("Fred");
      aMammalCage.insertAnimal(aFred);
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      Cage1<Mammal> aDogCage = new Cage1<Mammal>();
      aZoo.addCage(aDogCage);

      aDogCage.insertAnimal(new Mammal("Rover"));
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aDogCage.insertAnimal(new Mammal("Spot"));
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aMammalCage.removeAnimal(aFred);
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aBirdCage.clearCage();
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();

      aDogCage.clearCage();
      // tell zoo to check counts and update display
      aZoo.doCageUpdated();
   }
}
</pre>
<p>What we are forced to do, and must rely on, is that the developer writing the program will call the doCageUpdated() method on the zoo object every time an animal is added to a cage. See ZooTest1.java. This is not good programming practice.</p>
<h3>Implementing the Observer Pattern</h3>
<pre lang="Java" name="Cage2.java" colla="-">
public class Cage2<T extends Animal> {
   // List to hold our animals
   private List<T> animalList;

   // List to hold our observers
   private List<CageObserver> cageObservers;

   public Cage2() {
      animalList = new ArrayList<T>();
      cageObservers = new ArrayList<CageObserver>();
   }

   public void insertAnimal(T pAnimal) {
      animalList.add(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is added to the cage.");
      notifyObservers();
   }

   public void removeAnimal(T pAnimal) {
      animalList.remove(pAnimal);
      System.out.println("\n" + pAnimal.getName() + " " + pAnimal.getType()	+ " is removed from the cage.");
      notifyObservers();
   }

   public void clearCage() {
      animalList.clear();
      notifyObservers();
   }

   public List<T> getAnimals() {
      return animalList;
   }

   public void addCageObserver(CageObserver pCageObserver) {
      cageObservers.add(pCageObserver);
   }

   public void removeCageObserver(CageObserver pCageObserver) {
      cageObservers.remove(pCageObserver);
   }

   private void notifyObservers() {
      for (CageObserver aCageObserver : cageObservers) {
         aCageObserver.doCageUpdated();
      }
   }
}
</pre>
<pre lang="Java" name="Zoo2.java" colla="-">
public class Zoo2 implements CageObserver {
   private List<Cage2<? extends Animal>> cages;

   public Zoo2() {
      cages = new ArrayList<Cage2<? extends Animal>>();
   }

   public void addCage(Cage2<? extends Animal> pCage) {
      pCage.addCageObserver(this);
      cages.add(pCage);
   }

   public void removeCage(Cage2<? extends Animal> pCage) {
      pCage.removeCageObserver(this);
      cages.remove(pCage);
   }

   public void doCageUpdated() {
      Map<String, Integer> aAnimalCounts = getAnimalCounts();
      displayAnimalCounts(aAnimalCounts);
   }

   public Map<String, Integer> getAnimalCounts() {
      Map<String, Integer> aAnimalCounts = new HashMap<String, Integer>();
      for (Cage2<? extends Animal> aCage : cages) {
         List<? extends Animal> aAnimalList = aCage.getAnimals();
         int aCount = aAnimalList.size();
         if (aCount > 0) {
            String aType = aAnimalList.get(0).getType();
            Integer aTypeCount = aAnimalCounts.get(aType);
            if (aTypeCount == null) {
               aTypeCount = new Integer(aCount);
            } else {
               aTypeCount = new Integer(aTypeCount.intValue() + aCount);
            }
            aAnimalCounts.put(aType, aTypeCount);
         }
      }
      return aAnimalCounts;
   }

   public void displayAnimalCounts(Map<String, Integer> animalCounts) {

      Set<String> aAnimalSet = animalCounts.keySet();
      if (aAnimalSet == null || aAnimalSet.isEmpty()) {
         System.out.println("\nZoo is currently empty.");
      } else {
         System.out.println("\nCurrent zoo animal counts:");
      }
      for (String aType : aAnimalSet) {
         Integer aTypeCount = animalCounts.get(aType);
         System.out.println("There are " + aTypeCount.intValue() + " of type " + aType);
      }
   }
}
</pre>
<p>A better way is to implement the observer pattern. Look at Cage2.java, Zoo2.java, and ZooTest2.java. Looking at Cage2.java you can see that the Cage2 class now has another list, the list of CageObserver&#8217;s. Now, when an animal is added to the cage, the cage informs anyone that is listening that the cage count has changed. In our case, we just send a message that the cage is updated, but in a different design you may have passed the Cage2 object its self, or an interface, or another object that indicated the type of event (add, remove, clear) and the number of animals that it evolved. That is all up to your design. They would all fit the observer pattern.</p>
<pre lang="Java" name="ZooTest2.java" colla="-">
public class ZooTest2 {
   public static void main(String[] args) {

      Zoo2 aZoo = new Zoo2();

      Cage2<Bird> aBirdCage = new Cage2<Bird>();
      aZoo.addCage(aBirdCage);

      aBirdCage.insertAnimal(new Bird());
      aBirdCage.insertAnimal(new Bird());

      Cage2<Mammal> aMammalCage = new Cage2<Mammal>();
      aZoo.addCage(aMammalCage);

      Mammal aFred = new Mammal("Fred");
      aMammalCage.insertAnimal(aFred);

      Cage2<Mammal> aDogCage = new Cage2<Mammal>();
      aZoo.addCage(aDogCage);

      aDogCage.insertAnimal(new Mammal("Rover"));
      aDogCage.insertAnimal(new Mammal("Spot"));

      aMammalCage.removeAnimal(aFred);

      aBirdCage.clearCage();
      aDogCage.clearCage();
   }
}
</pre>
<p>Now look at the ZooTest2 class. Much better. No longer do we have to tell the zoo to display the data, it is done automatically. This may not seem that worthwhile here, but the process for adding cages to the zoo may not be connected with the process of adding animals to anyone cage. Keeping these things separate allows for more flexibility.</p>
<h3>Swinging the Observer Pattern</h3>
<p>We have already used the observer pattern in a previous lesson. Way back when we covered classes we looked at creating a Gui and implemented a WindowListener. We didn&#8217;t discuss it back then, but we were implementing the Observer Pattern. That&#8217;s right, every time we register an action listener of some sort in AWT, or Swing, we are registering an Observer with a Subject. Go back and look at Gui1 to Gui4. These are 4 different ways of creating the Observing class. As an example, here is Gui3.java.</p>
<pre lang="Java" name="Gui3.java" colla="+">
public class Gui3 extends JFrame {
   public Gui3() {
      setTitle("Gui3");
      setSize(300, 300);
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.out.println("Closeing Gui3");
            System.exit(0);
         }
      });
   }

   public static void main(String[] args) {
      JFrame aFrame = new Gui3();
      aFrame.setVisible(true);
   }
}
</pre>
<p>So keep this in mind. If you have written a GUI program, it is almost certain that you have implemented the Observer pattern. Swing depends heavily on it. That is how your visual components can react when users press buttons, move focus, and close windows. This way, you don&#8217;t have to create a loop of code that checks for a mouse click, and then determine which button the mouse was over, and then directs the program flow to specific code handling sections. You simple register with each button to be informed when it is clicked. And remember, several objects can register to listen at the same time. Because of this, Java even has a solution you can implement, called the EventListenerList. You can use this list in your classes to implement event listeners. Why reinvent it your self if it is already provided. This class supplies the underlying list, and methods to add and remove EventListeners to and from the List. It doesn&#8217;t supply a method to notify listeners in the list, but it does provide a method (getListeners()) that can take in a class type parameter so that you can ask the list to return just the listeners of a particular type. If you find you need to implement an observer event list, check this class out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-observer-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intro to Java Decorator Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-decorator-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-decorator-pattern/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 19:01:36 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[decorator]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pattern]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1284</guid>
		<description><![CDATA[We have looked at the Factory, the Adapter, and the Singleton patterns. Now we look at the Decorator. The Decorator is similar to the Adapter, but with a subtle difference. With our ReptileAdapter, we wrapped the Reptile class to map the interface methods of Animal to the appropriate methods on Reptile. With the Decorator we [...]]]></description>
			<content:encoded><![CDATA[<p>We have looked at the Factory, the Adapter, and the Singleton patterns. Now we look at the Decorator. The Decorator is similar to the Adapter, but with a subtle difference. With our ReptileAdapter, we wrapped the Reptile class to map the interface methods of Animal to the appropriate methods on Reptile. With the Decorator we also wrap a class, but to add functionality, not to map it or replace the functionality.</p>
<h3>The Decorator in the Physical World</h3>
<p>The idea behind decorating things in the real world is pretty much how it sounds. We wrap an object with new functionality, while keeping the old functionality. How about a camera in a waterproof housing? When closed up, we have added the functionality of waterproofing, but we still provide a way to press the buttons and turn the dials so that the camera can be operated.</p>
<h3>The Decorator in the Software World</h3>
<p>On the software side, the idea is the same. It is usually used when we have one object that we like how it functions, but we want to augment the behavior for a different situation. Done correctly, we can keep inserting one object inside another adding functionality at every step.<br />
<span id="more-1284"></span></p>
<h3>What do we need to create a Decorator?</h3>
<p>We need to create a class (our Decorator) that contains the class we want to decorate. We usually get this class into the Decorator using a constructor. Our Decorator needs to extend or implement the class or interface that contains the functionality we want to Decorate. Then when one of the methods of the decorated class is called, we call it before or after adding our own functionality.</p>
<h3>Ummm, Example?</h3>
<p>Lets use our Animals again. We are going to get a little bit emotional, or at least our animals are. Have you ever met people, who no matter what you ask them, has to tell you their emotional state? We will create an animal decorator that does just that. Every time we ask them to move() or speak() they will still move and speak, but they will also tell us their emotional state.</p>
<p>So, how do we accomplish this? Just as we could have done when we started looking at the Adapter, we could just go into the code for Animal or BaseAnimal and add new code to store a feeling, and put some getters and setters on it. But, our Animal code works, and not every animal likes to tell everyone they meet what they are feeling.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code14'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128414"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code" id="p1284code14"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> EmotionDecorator <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Animal decoratedAnimal<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> EmotionDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal <span style="color: #339933;">=</span> pDecoratedAnimal<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> decoratedAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      showEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      showEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> showEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;(Who by the way, is very &quot;</span> <span style="color: #339933;">+</span> getEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;.)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>So, we start by extending BaseAnimal. This means that we get all the functionality that is in BaseAnimal, and means that other objects can just treat us like an Animal. (BaseAnimal implements the Animal interface). We have a constructor that takes in an Animal to be decorated. Not every method is implemented by BaseAnimal however, so we provide the pass thru method for getType() and decorate move() and speak().</p>
<p>The getType() method does not add anything, but we still need to provide this pass thru method, because we want the decorated Animal&#8217;s type to be returned if someone asks us.</p>
<p>The move() and speak() methods get decorated. We first call the method on our decorated Animal, then we call showEmotion(). This does the same thing for both, it prints out how the animal is feeling. It gets its emotion from an abstract method. This allows us to push down the hierarchy to some small concrete classes just the specific behavior for each emotion. This does mean a different emotion class for each emotion, but it can be used for all animals. As an exercise, when this is over, try to create a EmotionDecorator that takes in a parameter for the emotion type instead.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code15'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128415"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code" id="p1284code15"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> HappyDecorator <span style="color: #000000; font-weight: bold;">extends</span> EmotionDecorator <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> HappyDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pDecoratedAnimal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getEmotion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;happy&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
Nothing to it. <span style="color: #006633;">It</span> just creates the constructor so our decorated animal is set up, and provides the correct emotion.
&nbsp;
<span style="color: #006633;">Lets</span> see an example of how we construct <span style="color: #000000; font-weight: bold;">this</span> decorator now.
<span style="color: #339933;">&lt;</span>pre lang<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;Java&quot;</span><span style="color: #339933;">&gt;</span>public <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   Animal aBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aHappyBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span>aBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   aBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aHappyBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here we create a Bird and we create a HappyDecorator that we put the bird into. If we call move() on aBird, we just get the move() method on bird. If we call the move() method on aHappyBird, we get the Bird.move() method called and the decoration.</p>
<p>We don&#8217;t have to create and hold an instance of Bird. We could just add them by doing a new inside the constructor of our decorator. We can even chain our emotions together to get one confused bird.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code16'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128416"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p1284code16"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   Animal aAngryBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aHappyBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aConfusedBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   aAngryBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aHappyBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aConfusedBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And just so you can see that we can decorate any of our Animals:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code17'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128417"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p1284code17"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
   Animal aAngryBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aHappyFish <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   Animal aConfusedMammal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AngryDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> HappyDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   aAngryBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aHappyFish.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aConfusedMammal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The chaining thing doesn&#8217;t look all that useful in this context, but it can be a great tool. Lets take a quick look at another example, the MovingDecorator. This is almost the same implementation as the EmotionDecorator, but we are only going to decorate the move() method. Lets throw a new twist in there too. Often with a Decorator, there is some sort of setup or initialization to do, so lets allow a way to init this decorator with a value, and have an abstract method to provide the values expected type.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code18'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128418"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code" id="p1284code18"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> MovingDecorator <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Animal decoratedAnimal<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> movementAmount<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> MovingDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal <span style="color: #339933;">=</span> pDecoratedAnimal<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> init<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> pMovementAmount<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      movementAmount <span style="color: #339933;">=</span> pMovementAmount<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> decoratedAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astringwriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">StringWriter</span></a> aWriter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astringwriter+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">StringWriter</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Move &quot;</span> <span style="color: #339933;">+</span> getMovement<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>movementAmount <span style="color: #339933;">!=</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> movementAmount<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> getMovementUnits<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      aWriter.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aWriter.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      decoratedAnimal.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovement<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovementUnits<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We now have a more complicated move method, but the idea is much the same. Decorate the object, then add functionality.</p>
<p>Once again we need to create concrete methods for the movement types. We have MoveForward, MoveLeft, and MoveRight.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code19'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128419"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1284code19"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MoveRightDecorator <span style="color: #000000; font-weight: bold;">extends</span> MovingDecorator <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> MoveRightDecorator<span style="color: #009900;">&#40;</span>Animal pDecoratedAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pDecoratedAnimal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovement<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;right&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getMovementUnits<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;degrees&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>These look almost the same as our Emotion ones, but we also have to implement a movement units method.</p>
<p>For our purposes we didn&#8217;t have to execute the init method, but we could. First is a simple class showing the using of this Decorator.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code20'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128420"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p1284code20"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   Animal aMammal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aMammal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Here shows chaining the move methods:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code21'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128421"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p1284code21"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   Animal aBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MoveLeftDecorator<span style="color: #009900;">&#40;</span>
   <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> MoveRightDecorator<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And finally, here we use the init method:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code22'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128422"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code" id="p1284code22"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   Animal aBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   MovingDecorator aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span>aBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveRightDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveLeftDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">90</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MoveForwardDecorator<span style="color: #009900;">&#40;</span>aDecoBird<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">//What happens when this is uncommented?</span>
   <span style="color: #666666; font-style: italic;">//aDecoBird = new HappyDecorator(aBird);</span>
&nbsp;
   aDecoBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   aDecoBird.<span style="color: #006633;">speak</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>If you noticed, I actually created a MovingDecorator instead of an Animal here, and that was simply so that I didn&#8217;t have to keep casting to call the init method.</p>
<h3>How about in the Java SDK?</h3>
<p>One of the best examples is the FileIO section. This is the code that allows you to read and write to the file system. You start with a basic byte or character reader, then wrap with decorators that can read by lines, or buffer for more performance.</p>
<p>You can learn about file IO in this <a href="http://java.sun.com/docs/books/tutorial/essential/io/">sun trail</a>.</p>
<p>If you remember from the Reflection Session, we read data from a properties file. We will access a file the same way here. This is shown so you can see what it looks like with no decoration.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code23'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128423"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1284code23"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> IODecoratorTest1 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Exception</span></a> <span style="color: #009900;">&#123;</span>
&nbsp;
      <span style="color: #000066; font-weight: bold;">int</span> c<span style="color: #339933;">;</span>
&nbsp;
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstream+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStream</span></a> aStream <span style="color: #339933;">=</span> IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span> c <span style="color: #339933;">=</span> aStream.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;=</span> <span style="color: #cc66cc;">0</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#41;</span>c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      aStream.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>IODecoratorTest2 shows how we decorate the input stream. First with InputStreamReader, then with BufferedReader, then finally adding a LineNumberReader.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code24'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128424"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code" id="p1284code24"><pre class="java" style="font-family:monospace;"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> aReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>
.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> aReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Abufferedreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">BufferedReader</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>
IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> aReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alinenumberreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">LineNumberReader</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Abufferedreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">BufferedReader</span></a><span style="color: #009900;">&#40;</span>
<span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>IODecoratorTest2.<span style="color: #000000; font-weight: bold;">class</span>
.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>So, as you can see, we are layering, or stacking the classes. We are decorating the read() methods in each of these classes to add behavior. We can do the same thing. Lets write a Reader decorator ourselves that can count the number of times ‚ÄòI&#8217; is in the file.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code25'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128425"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code" id="p1284code25"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ICountReader <span style="color: #000000; font-weight: bold;">extends</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Afilterreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">FilterReader</span></a> <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> inReader<span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> count<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> ICountReader<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Areader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Reader</span></a> pInReader<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pInReader<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      inReader <span style="color: #339933;">=</span> pInReader<span style="color: #339933;">;</span>
      count <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> read<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aioexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">IOException</span></a> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">int</span> aByte <span style="color: #339933;">=</span> inReader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>aByte <span style="color: #339933;">==</span> <span style="color: #0000ff;">'I'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         count<span style="color: #339933;">++;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #000000; font-weight: bold;">return</span> aByte<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> read<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> cbuf, <span style="color: #000066; font-weight: bold;">int</span> off, <span style="color: #000066; font-weight: bold;">int</span> len<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aioexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">IOException</span></a> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">int</span> n <span style="color: #339933;">=</span> inReader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span>cbuf, off, len<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> off<span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> off <span style="color: #339933;">+</span> n<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #000066; font-weight: bold;">int</span> c <span style="color: #339933;">=</span> cbuf<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
         <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c <span style="color: #339933;">==</span> <span style="color: #0000ff;">'I'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            count<span style="color: #339933;">++;</span>
         <span style="color: #009900;">&#125;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #000000; font-weight: bold;">return</span> n<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getICount<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> count<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>We are extending FilterReader instead of implementing the Reader interface so we don&#8217;t have quite so many methods to implement. This is just the same as the other decorators we have been looking at. We can insert it into a decorator chain just the same way.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1284code26'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p128426"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code" id="p1284code26"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> IODecoratorTest3 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Exception</span></a> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">int</span> c<span style="color: #339933;">;</span>
      ICountReader aICountReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ICountReader<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Abufferedreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">BufferedReader</span></a><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainputstreamreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">InputStreamReader</span></a><span style="color: #009900;">&#40;</span>IODecoratorTest1.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;ioTest.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alinenumberreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">LineNumberReader</span></a> aLineReader <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alinenumberreader+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">LineNumberReader</span></a><span style="color: #009900;">&#40;</span>aICountReader<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>c <span style="color: #339933;">=</span> aLineReader.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;=</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#41;</span> c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      aLineReader.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// We cast because we need a ICountRe to ask for the line</span>
      <span style="color: #666666; font-style: italic;">// number, and it is zero based so we add one</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;# of I's:&quot;</span> <span style="color: #339933;">+</span> aICountReader.<span style="color: #006633;">getICount</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;# of lines:&quot;</span> <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span>aLineReader.<span style="color: #006633;">getLineNumber</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-decorator-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Singleton Pattern</title>
		<link>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/</link>
		<comments>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/#comments</comments>
		<pubDate>Mon, 08 Jun 2009 21:53:37 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1273</guid>
		<description><![CDATA[The last pattern we looked at was the Adapter pattern. It was a good pattern to start with as it maps well to the physical world and is fairly simple. Now we will look at the Singleton pattern. In some respects it is the simplest of patterns, but there are some things to think about.
The [...]]]></description>
			<content:encoded><![CDATA[<p>The last pattern we looked at was the Adapter pattern. It was a good pattern to start with as it maps well to the physical world and is fairly simple. Now we will look at the Singleton pattern. In some respects it is the simplest of patterns, but there are some things to think about.</p>
<h3>The Singleton in the Physical World</h3>
<p>The idea behind the Singleton is to ensure that there can be only one (insert Highlander jokes here). If you had a factory that made widgets, you would want a widget to be created many many times. But there is only one factory. If you were modeling the US government, you would only want one president. Only one senate.</p>
<h3>The Singleton in the Software World</h3>
<p>On the software side, the idea is the same. It is usually used when we only want one set of configuration variables, one controller, one data base connection pool, that kind of thing.<br />
<span id="more-1273"></span></p>
<h3>How do we do this?</h3>
<p>Let&#8217;s back up a bit. Let us look at a very basic class that provides us with a code that is needed across our application.</p>
<pre lang="Java" name="MyClass.java" colla="+">
public class MyClass {

   private long code;

   public MyClass() {
      code = Calendar.getInstance().getTimeInMillis();
   }

   public long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MyClassTest.java" colla="-">
public class MyClassTest {
   public static void main(String[] args) throws Exception {

      MyClass myClass1 = new MyClass();
      System.out.println(myClass1.getCode());

      Thread.sleep(500);// wait a bit to see if our code is the same

      MyClass myClass2 = new MyClass();
      System.out.println(myClass2.getCode());

      System.out.println("Oops. Different values.");
   }
}
</pre>
<p>If you only ever instantiated this class once, you are fine. But we haven&#8217;t done anything here to ensure that this is the case. There is nothing to stop someone from creating two MyClass objects.</p>
<p>Let&#8217;s start with the opposite. How do we create an instance of a class?</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1273code29'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p127329"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p1273code29"><pre class="java" style="font-family:monospace;">MyClass myClass1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
MyClass myClass2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MyClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>What can we do to ensure that only one instance can be created? Is there something else we have looked at that allows only one instance of a variable to occur? Static! We can use the static property.</p>
<pre lang="Java" name="MyStaticClass.java" colla="+">
public class MyStaticClass {

   private static long code = Calendar.getInstance().getTimeInMillis();

   public static long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MyStaticClassTest.java" colla="-">
   public static void main(String[] args) throws Exception {

      MyStaticClass myClass1 = new MyStaticClass();
      System.out.println(MyStaticClass.getCode());
      System.out.println(myClass1);

      Thread.sleep(500);// wait a bit to make sure our code is the same

      MyStaticClass myClass2 = new MyStaticClass();
      System.out.println(MyStaticClass.getCode());
      System.out.println(myClass2);

      System.out.println("Ok. Same values.");
      System.out.println("Oops, different objects.");

   }
}
</pre>
<p>This time we have assigned a static variable our code, and provided a static method for accessing this code. Does this work? Somewhat. We only have one instance of code inside of MyStaticClass, but MyStaticClass is not guaranteed to have only one instance. This will get cumbersome to initialize as we add other data. It also results in a bunch of MyStaticClass.getCode() all over the application. What would be better would be to ask for this class just once, and then call getCode() as needed. How can we set that up?</p>
<h3>The Simplest Singleton</h3>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1273code30'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p127330"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code" id="p1273code30"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Singleton <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> Singleton singleton<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">private</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Singleton getInstance<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> singleton <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         singleton <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Singleton<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #000000; font-weight: bold;">return</span> singleton<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This example doesn&#8217;t have our &#8220;code&#8221; in it, but it does show the elements of the singleton. We will add the &#8220;code&#8221; later.</p>
<p>There are some interesting things about this class. Look at the constructor. It is private! How does that work? We can&#8217;t do a &#8220;new&#8221; on this class! How can we create it? There is a private member variable that is static, and is of the same type as the class! It is a very strange sight at first glance. What is going on?</p>
<p>The constructor being private accounts for our first goal. No ability to call &#8220;new&#8221; on the object. If we can&#8217;t do a &#8220;new&#8221;, how can we create it? Well, we can do a &#8220;new&#8221;, but only from inside the class itself. We are doing that in the static getInstance() method. Look at what that method does. It first checks to see if an instance of the member variable singleton exists. If it doesn&#8217;t, it creates a &#8220;new&#8221; instance. This is the only place we will ever create an instance of the class Singleton. Therefore we have ensured that this is the only copy available. We then return singleton.</p>
<p>By doing things this way we have also lazy initialized the singleton. If we don&#8217;t need it, we never call getInstance(), and we never have to worry about the JVM allocating memory for something not used.</p>
<p>We also get a normal looking class out of it. We can have standard getters that are not static, and our application can pass this object around. It is easier to conceptualize the object used this way, and do maintenance later than a bunch of static methods seemingly randomly called within methods.</p>
<h3>Can we actually do something?</h3>
<p>Ok, I get your point. We need a bit more of an example. So here is a singleton with one &#8220;code&#8221; just like the others.</p>
<pre lang="Java" name="MySingletonClass.java" colla="+">
public class MySingletonClass {

   private static MySingletonClass singleton;

   private long code;

   private MySingletonClass() {
      code = Calendar.getInstance().getTimeInMillis();
   }

   public static MySingletonClass getInstance() {

      if ( singleton == null ) {
         singleton = new MySingletonClass();
      }
      return singleton;
   }

   public long getCode() {
      return code;
   }
}
</pre>
<pre lang="Java" name="MySingletonClassTest.java" colla="-">
public class MySingletonClassTest {
   public static void main(String[] args) throws Exception {

      MySingletonClass mySingletonClass1 = MySingletonClass.getInstance();
      System.out.println(mySingletonClass1.getCode());
      System.out.println(mySingletonClass1);

      Thread.sleep(500); //wait a bit to make sure our code is the same

      MySingletonClass mySingletonClass2 = MySingletonClass.getInstance();
      System.out.println(mySingletonClass2.getCode());
      System.out.println(mySingletonClass2);

      System.out.println("yea, same code");
      System.out.println("yea, same object");
   }
}
</pre>
<p>Look at that. Other than the singleton field, the constructor marked as private, and the getInstance() method, it is a pretty normal looking class. The constructor initializes our class just as we would expect. We can have pretty standard fields, like &#8220;code&#8221; with normal public getters.</p>
<h3>Is that all there is to it?</h3>
<p>Yup. It is that easy. Almost. Sometimes. There is one more wrinkle. Depending on how this singleton is being used, you may need to account for multiple threads. I am not going to get into that here, as we haven&#8217;t looked at threads yet. Keep in mind that if multiple objects could all call getInstance() at the same time, you may have an issue. Look it up, or wait and see if I get to threads eventually <img src='http://www.cyberward.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<h3>Why use the pattern?</h3>
<ul>
<li>Ensures only one instance of your code with minimal fuss.</li>
<li>The singleton can be assigned.</li>
<li>Uses lazy initialization to save memory.</li>
<li>It is proven. It works. You can try to avoid the pattern, but why bother?</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/06/intro-to-java-singleton-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Annotations</title>
		<link>http://www.cyberward.net/blog/2009/05/intro-to-java-annotations/</link>
		<comments>http://www.cyberward.net/blog/2009/05/intro-to-java-annotations/#comments</comments>
		<pubDate>Sat, 30 May 2009 19:13:09 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1225</guid>
		<description><![CDATA[Annotations allow you to attach metadata to a field, class, or method. Metadata is data that describes something else. For example, metadata about a song in mp3 format could be the artists name or the bit rate it was encoded at.  A jpeg image could have metadata that described the image height or the [...]]]></description>
			<content:encoded><![CDATA[<p>Annotations allow you to attach metadata to a field, class, or method. Metadata is data that describes something else. For example, metadata about a song in mp3 format could be the artists name or the bit rate it was encoded at.  A jpeg image could have metadata that described the image height or the number of colors in the image.</p>
<h3>What do they look like?</h3>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code39'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122539"><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code" id="p1225code39"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;no name&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The word after the ‚Äò@‚Äô is the Annotation. It precedes a method or class name. The Override annotation is built into Java. It is used to indicate that a method overrides a parents method. These are used for compiler hinds, for documentation, and to apply meta data.<br />
<span id="more-1225"></span></p>
<h3>Built in Annotations</h3>
<ul>
<li>@Deprecated : used much like the java doc comment</li>
<li>@Override ‚Äì indicates a method overrides a parents method</li>
<li>@SuppressWarnings ‚Äì tells compiler not to indicate warnings</li>
<li>@Documented ‚Äì tells javadoc to document the applied Annotations</li>
<li>@Retention(RetentionPolicy.xxx) ‚Äì indicate to compiler when the Annotation is available</li>
</ul>
<p>Take a look at the Bird.getName() method, and the Animal.getType() method to see a couple of Annotations. Theese classes have been altered slightly here to add some annotations. AnnotationsTest1 shows what you will see in eclipse, or if you compile a deprecated method. AnnotationsTest2 shows how you can use @SupressWarnings.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code40'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122540"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code" id="p1225code40"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> Animal <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setName<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> pName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #008000; font-style: italic; font-weight: bold;">/**
    * @ deprecated This will not work in the future
    */</span>
   @Deprecated
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code41'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122541"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code" id="p1225code41"><pre class="java" style="font-family:monospace;">@Ratable<span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span><span style="color: #cc66cc;">8</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Bird <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> Bird<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> pName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>pName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Bird created.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Ratable<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">6</span><span style="color: #009900;">&#41;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> move<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>getDescription<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; is flying.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Ratable<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> speak<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>getDescription<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; chirps.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #008000; font-style: italic; font-weight: bold;">/**
    * Can't use @Override because it is an interface method
    */</span>
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;bird&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @Override
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;no name&quot;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code42'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122542"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code" id="p1225code42"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AnnotationsTest1 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
      Fish aFish <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aFish.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// this line in Eclipse show a strike through on the method</span>
      <span style="color: #666666; font-style: italic;">// when compiling with warnings you would get the error too</span>
      aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code43'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122543"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code" id="p1225code43"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AnnotationsTest2 <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> doWithOutGenerics<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// without generics compiler gives warning about generic type</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   @SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> doWithAnnotations<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// adding annotation to remove compiler warning</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> doWithGenerics<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// add type to List and ArrayList</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Creating your own Annotations</h3>
<p>If you would like to create your own Annotations, it is not very hard. For example look at the Ratable Annotation.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code44'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122544"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code" id="p1225code44"><pre class="java" style="font-family:monospace;">@Documented
@Retention<span style="color: #009900;">&#40;</span>RetentionPolicy.<span style="color: #006633;">RUNTIME</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> @<span style="color: #000000; font-weight: bold;">interface</span> Ratable <span style="color: #009900;">&#123;</span>
&nbsp;
   <span style="color: #000066; font-weight: bold;">int</span> value<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000066; font-weight: bold;">int</span> rating<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
&nbsp;
   <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> why<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">default</span> <span style="color: #0000ff;">&quot;because&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>The class is defined as an @Interface. This makes it an annotation. The strange method definitions that follow are the types of meta data that this annotation can contain. This one can have a value, a rating, and a why. One of the neat things, is that you can provide defaults in the case that someone using your annotation does not provide values for them. So how would you apply this annotation?</p>
<p>Look at the first couple of lines from Fish.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code45'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122545"><td class="line_numbers"><pre>1
2
</pre></td><td class="code" id="p1225code45"><pre class="java" style="font-family:monospace;">@Ratable<span style="color: #009900;">&#40;</span>rating <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span>, why <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;Smells Bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Fish <span style="color: #000000; font-weight: bold;">extends</span> BaseAnimal <span style="color: #009900;">&#123;</span></pre></td></tr></table></div>

<p>The Ratable annotation has been applied to the class Fish with a rating of 2, a value of 0 (default) and a why of ‚ÄúSmells Bad‚Äù.</p>
<h3>Why would you want your own Annotations?</h3>
<p>Why would create your own? If you create an annotation, you can use them with compiler tools to provide information. If you specify a RetentionPolicy of Runtime, then you can use your annotation at Runtime. What good would that be? Think about MP3 files. You can do a search of all your music for all music files that are by a certain author. You can do that with annotations of your classes as well. You can use annotations instead of using instanceof. You can also scan the class path to look for annotations.</p>
<p>Several well know packages and utilities have started to use annotations for configuration. Struts2, JBoss, and hibernate are some you may have heard about. This idea allows you to specify configuration right in the classes themselves instead of in separate XML or properties files.</p>
<p>The Java reflections API provides some help for dealing with these as runtime, but libraries have been created that help with this. One such library is also called ‚Äúreflections‚Äù. AnnotationsTest3 is an example that uses this API.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1225code46'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122546"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code" id="p1225code46"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AnnotationsTest3 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      AbstractConfiguration configuration <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> AbstractConfiguration<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
      configuration.<span style="color: #006633;">setUrls</span><span style="color: #009900;">&#40;</span>ClasspathHelper.<span style="color: #006633;">getUrlsForCurrentClasspath</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      configuration.<span style="color: #006633;">setScanners</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ClassAnnotationsScanner<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      configuration.<span style="color: #006633;">setFilter</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> IncludePrefix<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;net.cyberward.tutorial.java.annotations&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Reflections reflections <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Reflections<span style="color: #009900;">&#40;</span>configuration<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      Set<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> annotated <span style="color: #339933;">=</span> reflections.<span style="color: #006633;">getTypesAnnotatedWith</span><span style="color: #009900;">&#40;</span>Ratable.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> aAnnotatedClass <span style="color: #339933;">:</span> annotated<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         Ratable aRateableAnnotation <span style="color: #339933;">=</span> aAnnotatedClass.<span style="color: #006633;">getAnnotation</span><span style="color: #009900;">&#40;</span>Ratable.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnnotatedClass<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aRateableAnnotation<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;rateing:&quot;</span><span style="color: #339933;">+</span>aRateableAnnotation.<span style="color: #006633;">rating</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>More Information:</h3>
<ul>
<li><a href="http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html">http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html</a></li>
<li><a href="http://en.wikipedia.org/wiki/Java_annotation">http://en.wikipedia.org/wiki/Java_annotation</a></li>
<li><a href="http://www.javabeat.net/articles/30-annotations-in-java-50-1.html">http://www.javabeat.net/articles/30-annotations-in-java-50-1.html</a></li>
<li><a href="http://code.google.com/p/reflections/">http://code.google.com/p/reflections/</a></li>
</ul>
<p><strong>Note:</strong> If you are using Eclipse and do a ‚ÄúRefactor / Rename‚Ä¶‚Äù of an Annotation, all the places that use the Annotation will be modified too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/intro-to-java-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Setting up Linux Software Raid</title>
		<link>http://www.cyberward.net/blog/2009/05/setting-up-linux-software-raid/</link>
		<comments>http://www.cyberward.net/blog/2009/05/setting-up-linux-software-raid/#comments</comments>
		<pubDate>Sat, 30 May 2009 12:00:55 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Computers]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mdadm]]></category>
		<category><![CDATA[raid]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=973</guid>
		<description><![CDATA[This is part of our series on building a NAS. In this article we will get the box set up with a static IP address, and get your drives set up for RAID 1.
We are assuming that at this point you have Ubuntu installed. We are gong to install software raid in a moment. The [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-1204" title="Dual Drives for Raid 1" src="http://www.cyberward.net/blog/wp-content/uploads/dualdrive.jpg" alt="Dual Drives for Raid 1" width="329" height="173" />This is part of our series on building a NAS. In this article we will get the box set up with a static IP address, and get your drives set up for RAID 1.</p>
<p>We are assuming that at this point you have Ubuntu installed. We are gong to install software raid in a moment. The first thing I want to do is make sure we have a static ip address. Usually Ubuntu will start up with a dynamic ip address. This can make it more difficult to transfer files to this box, so lets make it static.<br />
<span id="more-973"></span></p>
<h3>Setting a static IP address</h3>
<p>Type ifconfig eth0, and you will see your current address.</p>
<p>Lets make it static. Note, typing sudo in front of commands lets you assume the privileges of the administrator, or super user.</p>
<pre class="linux">sudo nano /etc/network/interfaces</pre>
<p>We will replace the text there with this text, which will assign 10.0.0.50 to our server, and assume the gateway is at 10.0.0.1:</p>
<pre class="linux">auto eth0
iface eth0 inet static
address 10.0.0.50
netmask 255.255.255.0
network 10.0.0.0
broadcast 10.0.0.255
gateway 10.0.0.1</pre>
<p>restart the network to get the new settings :</p>
<pre class="linux">sudo /etc/init.d/networking restart</pre>
<p>ifconfig eth0 and you should see the new settings.</p>
<p>If you want to see a whole lot more networking commands, see <a href="http://www.cyberciti.biz/tips/howto-ubuntu-linux-convert-dhcp-network-configuration-to-static-ip-configuration.html">here</a>.</p>
<h3>Finding out drives</h3>
<p>Great. Now before we can put two drives into a RAID 1 array, we need to tell linux what drives we are going to use for this.</p>
<p>How do we know what disks? I just type dmesg. This will scroll lots of stuff down the screen. If you are in the GUI at a terminal you can scroll. Otherwise type dmesg | less which will let you move through the text with the cursor keys.</p>
<p>This is all the hardware that was found and initialized. You will first see the ataX with X being the number of the drive. You need to look for a section after this that has letters like hda or sda. The drives I am using are SATA drives and they are <strong>sda</strong> and <strong>sdb</strong>. I could tell by the size of the drives. (press Q to exit less if you need to)</p>
<h3>Partition¬†for Raid 1</h3>
<p>Ok, lets tell Linux that we want those drives to be used for raid.</p>
<pre class="linux">sudo fdisk /dev/sda</pre>
<p>[p] will list the partitions. If you had one previously, you will see it. Remove them. Press d for delete, then give a partition number. (no need if you only had one)</p>
<p>Now add a [n]ew [p]rimary partition number [1] with default start and end (the whole disk)</p>
<pre class="linux">n [enter] p [enter] 1 [enter][enter][enter]</pre>
<p>Now [p] again to verify that the partition is there. Note the type: 83. Type [l] to see all the types. We need to set the type to fd for Linux software raid.</p>
<pre class="linux">t [enter] fd [enter]</pre>
<p>Now write the partition table and exit: w [enter]</p>
<p>Now we repeat the process with the other drive.</p>
<pre class="linux">sudo fdisk /dev/sdb</pre>
<p>And repeat the fdisk commands.</p>
<h3>Setting up mdadm for Raid1</h3>
<p>Ok, now for Linux software raid. First we need to install it.</p>
<pre class="linux">sudo apt-get install mdadm</pre>
<p>When I did this, I was prompted that citadel-server was being installed. This is what is used by default as the mail server. Mdadm is dependant on a mail server so it can mail you of failures. Pick an admin user and say no to external auth.</p>
<p>Once installed you can build an array. I am going to use two drives in a RAID 1, mirrored setup. This duplicates all the data on both drives. They are mirrored. This is the command with my drives used. You will substitute for your devices:</p>
<pre class="linux">sudo mdadm --create --verbose /dev/md0 --level=1 --raid-devices=2 /dev/sda1 /dev/sdb1</pre>
<p>This should tell you that the array /dev/md0 has started.</p>
<p>If you would like to see when the array is built:</p>
<pre class="linux">cat /proc/mdstat</pre>
<p>This will tell you how long it will take, or if it is done.</p>
<p>Ok, that&#8217;s it for now.¬† We will look at commands to manipulate the array in a later article in the series. Next up will be creating the resizable volumes on the array using LVM.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/setting-up-linux-software-raid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Building a NAS]]></series:name>
	</item>
		<item>
		<title>Intro to Java Generics</title>
		<link>http://www.cyberward.net/blog/2009/05/intro-to-java-generics/</link>
		<comments>http://www.cyberward.net/blog/2009/05/intro-to-java-generics/#comments</comments>
		<pubDate>Fri, 29 May 2009 14:00:55 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1220</guid>
		<description><![CDATA[To me it seems a better word would be Specifics. The use of Generics is applying a specific type to a class that can be used in a generic way. One of the most common generic classes is List. A list allows you to put any type of Object in to it. In fact, you [...]]]></description>
			<content:encoded><![CDATA[<p>To me it seems a better word would be Specifics. The use of Generics is applying a specific type to a class that can be used in a generic way. One of the most common generic classes is List. A list allows you to put any type of Object in to it. In fact, you can put several different types of Objects into a List. But, there is a way to create a specific List type that can only take one type of Object.</p>
<h3>What do they look like?</h3>
<p>Since we are talking about Lists, lets look at what a ArrayList would look like that could only take Strings.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code57'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122057"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p1220code57"><pre class="java" style="font-family:monospace;"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>What goes between the &lt;&gt; is the type that you want to specify for the List. You need to do it in the left side declaration, and on the right side where you are creating the Object.<br />
<span id="more-1220"></span></p>
<h3>Does this work for all classes?</h3>
<p>A class has to be specifically defined for generics. All the collections have been defined this way, and you can create your own classes like this too.</p>
<p>Lets look at the class definition of List:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code58'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122058"><td class="line_numbers"><pre>1
</pre></td><td class="code" id="p1220code58"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> <span style="color: #000000; font-weight: bold;">extends</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Acollection+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Collection</span></a> <span style="color: #009900;">&#123;</span></pre></td></tr></table></div>

<p>Now lets look at methods such as add and get:</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code59'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122059"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p1220code59"><pre class="java" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">boolean</span> add<span style="color: #009900;">&#40;</span>E o<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
E get<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> index<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>In the definition, between the &lt;&gt; List is defined to have a variable E that will contain a class type. (It is always a class type.) This variable can be used anywhere you want to specify this class type. In the case of the add() method, it means that the add method can only accept Objects of the class type E. For the get method, it means that the get method returns an Object of type E.</p>
<h3>How is any of this useful?</h3>
<p>Well, first of all, if you have your compiler set up to compile at a Java 5 level, adding these types removes all the compiler warnings. In Eclipse it will remove all the yellow warnings that are annoying.</p>
<p>More importantly, it allows you to limit the type that you take in with your methods.</p>
<p>GenericsTest1 serves as an example of how you would apply generics to a List.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code60'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122060"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code" id="p1220code60"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> GenericsTest1 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// Create a List without specifying type parameters</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList1.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList1.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList1.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Does compiler complain? Does it work at runtime?</span>
      <span style="color: #666666; font-style: italic;">//aList1.add(new Object());</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> aList1.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #666666; font-style: italic;">//notice the need for a cast</span>
         Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         aAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Create a List and specify that only an Animal can be used.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList2.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList2.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aList2.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Does compiler complain? Does it work at runtime?</span>
      <span style="color: #666666; font-style: italic;">//aList2.add(new Object());</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> aList2.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #666666; font-style: italic;">// notice no casting</span>
         Animal aAnimal <span style="color: #339933;">=</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         aAnimal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>GenericsTest2 shows a similar example, but using a Map.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code61'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122061"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
</pre></td><td class="code" id="p1220code61"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> GenericsTest2 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Integer</span></a> aIntegerKey <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ainteger+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Integer</span></a><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Create a Map without specifying type parameters</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Amap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Map</span></a> aMap1 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ahashmap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">HashMap</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap1.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap1.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Notice that there is no restriction on the key type</span>
      aMap1.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>aIntegerKey, <span style="color: #000000; font-weight: bold;">new</span> Mammal<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aBird <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> aMap1.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBird.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aFish <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> aMap1.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aFish.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aMammal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> aMap1.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>aIntegerKey<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMammal.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Create a Map an specify that only a String key and an Animal value</span>
      <span style="color: #666666; font-style: italic;">// can be used in the map.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Amap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Map</span></a> aMap2 <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Ahashmap+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">HashMap</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap2.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aMap2.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// What happens when this is uncommented</span>
      <span style="color: #666666; font-style: italic;">//aMap2.put(aIntegerKey, new Mammal());</span>
&nbsp;
      Animal aBird2 <span style="color: #339933;">=</span> aMap2.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bird&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBird2.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Animal aFish2 <span style="color: #339933;">=</span> aMap2.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fish&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aFish2.<span style="color: #006633;">move</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">//What happens when this is uncommented. Compiler? Run time? Why?</span>
      <span style="color: #666666; font-style: italic;">//Animal aMammal2 = aMap2.get(aIntegerKey);</span>
      <span style="color: #666666; font-style: italic;">//aMammal2.move();</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now lets rewrite a couple of things to use generics.</p>
<p>Look at the CollectionUtilities.printAnimalList() method from the ‚ÄúIntro to Java Collections‚Äù lesson.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code62'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122062"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p1220code62"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> printAnimalList<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> pAnimalList.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// notice the need for a cast</span>
      Animal aAnimal <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Animal<span style="color: #009900;">&#41;</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>You can‚Äôt get much more un type safe than this. We define the method to only take in a List. But in the code we expect to only have Animals. We also have to cast to an Animal because when the List is created we don‚Äôt define a specific type, so the list can contain any type of Object.</p>
<p>Lets rewrite this method using generics.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code63'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122063"><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code" id="p1220code63"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> printAnimalList<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aiterator+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">Iterator</span></a> iterator <span style="color: #339933;">=</span> pAnimalList.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> iterator.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// notice no casting</span>
      Animal aAnimal <span style="color: #339933;">=</span> iterator.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Our method definition has determined that only Lists that contain Animal types are allowed. If someone tried to use this method with a List of Strings, the compiler would not let it happen. Also notice that we no longer need to cast from this Iterator. That is because the .iterator() method in List returns a  Iterator, and Iterator doesn‚Äôt return just an Object, but one of the Animal type.</p>
<p>Even better, lets use a new Java 5 looping structure called a ‚Äúfor each‚Äù loop. This works for any class that implements the Iterable interface (like List).</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code64'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122064"><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code" id="p1220code64"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> printAnimalList<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Animal aAnimal <span style="color: #339933;">:</span> pAnimalList<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span> <span style="color: #339933;">+</span> aAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now lets look at Cage. Cage is a version of a cage that allows you to specify what type of animal the cage contains using generics. See GenericsTest3. This is not quite the same as BirdCage, it is not a singleton, but BirdCage could also be rewritten so that it could be a cage for any animal, not just birds. Try to rewrite it using this Cage as an example.</p>

<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code65'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122065"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code" id="p1220code65"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Cage <span style="color: #009900;">&#123;</span>
   <span style="color: #666666; font-style: italic;">// We can then use T to define our list class type</span>
   <span style="color: #000000; font-weight: bold;">private</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> animalList<span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> Cage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// When we create the list we must tell it a type too.</span>
      animalList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// We can even specify in a method signature that only objects of type T are</span>
   <span style="color: #666666; font-style: italic;">// allowed to be here. Not just any Animal, but just of class type T.</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> insertAnimal<span style="color: #009900;">&#40;</span>T pAnimal<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      animalList.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>pAnimal<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>pAnimal.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> pAnimal.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; is in the cage.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #666666; font-style: italic;">// When we return our list, it will be a list that only contains class type</span>
   <span style="color: #666666; font-style: italic;">// T, and you won't need to cast individual elements from the list.</span>
   <span style="color: #000000; font-weight: bold;">public</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> getAnimals<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">return</span> animalList<span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>


<div class="wp_codebox_msgheader wp_codebox_hide"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1220code66'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p122066"><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code" id="p1220code66"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> GenericsTest3 <span style="color: #009900;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">// Without specifying type parameters the compiler gives us all kinds of warnings.</span>
      Cage aCage <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// Notice that because we didn't specify a type when we created the</span>
      <span style="color: #666666; font-style: italic;">// Cage, we can actually add a fish.</span>
      aCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Fish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Lets add parameters.</span>
      Cage aBirdCage <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Cage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBirdCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      aBirdCage.<span style="color: #006633;">insertAnimal</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bird<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #666666; font-style: italic;">// What happens when this is uncommented</span>
      <span style="color: #666666; font-style: italic;">// aBirdCage.insertAnimal(new Fish());</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// You can get back a non parameterized list, and it is functional, but</span>
      <span style="color: #666666; font-style: italic;">// you get a warning from the compiler.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList2 <span style="color: #339933;">=</span> aBirdCage.<span style="color: #006633;">getAnimals</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aList2.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">// Add the type parameter to list to make the compiler happy.</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aBirdList <span style="color: #339933;">=</span> aBirdCage.<span style="color: #006633;">getAnimals</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>aBirdList.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Letter Conventions</h3>
<p>There is no restriction on what letters you can use in your class definitions and method signatures. In fact, instead of ‚ÄúT‚Äù you could use ‚ÄúQQ‚Äù or ‚ÄúType‚Äù. It seems that the Java authors have settled on using just one letter, and they themselves have been fairly consistent about the letters they use.</p>
<p>In the collections packages they usually use ‚ÄúE‚Äù for element. So when you look at the interface for List, you will see .</p>
<p>If you look at the Map interface, you will see  for Key and Value.</p>
<p>Also, other classes that take in a class type usually use the letter ‚ÄúT‚Äù for type.</p>
<h3>More Information:</h3>
<ul>
<li><a href="http://java.sun.com/docs/books/tutorial/java/generics/index.html">http://java.sun.com/docs/books/tutorial/java/generics/index.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html">http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html</a></li>
<li><a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf">http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf (pdf)</a></li>
<li><a href="http://en.wikipedia.org/wiki/Generics_in_Java">http://en.wikipedia.org/wiki/Generics_in_Java</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/intro-to-java-generics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Intro to Java Collections</title>
		<link>http://www.cyberward.net/blog/2009/05/intro-to-java-collections/</link>
		<comments>http://www.cyberward.net/blog/2009/05/intro-to-java-collections/#comments</comments>
		<pubDate>Thu, 28 May 2009 16:09:13 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1212</guid>
		<description><![CDATA[I don&#8217;t want to get too deep into every little thing in the collections classes here. In fact, you already know a fair bit about them, because we have used them with some of our Animal class examples. This is more an overview of some of the basic Collections classes.
What do they look like?
There are [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t want to get too deep into every little thing in the collections classes here. In fact, you already know a fair bit about them, because we have used them with some of our Animal class examples. This is more an overview of some of the basic Collections classes.</p>
<h3>What do they look like?</h3>
<p>There are three main types of collections: Lists, Maps, and Sets. Technically you could try to argue that Map doesn&#8217;t extend Collection, so therefore it is not a Collection, but I think of it as part of the group.<br />
They are used for groups of objects, or exactly as its name would imply, collections of objects.</p>
<h3>List</h3>
<p>A List is just that, a list of objects. The List interface provides a way to add, remove and get objects from a list. It however is just an interface. ArrayList is one of the more popular concrete collections that implements the List interface. Each implementation of the List interface may behave slightly different, but once you understand how a List works, you have a good start on understanding any List.<br />
<span id="more-1212"></span><br />
An ArrayList can be thought of in some ways like an Array, but there are some differences. One of the biggest is that you can keep adding or removing from an ArrayList (or any List) without needing to have defined it in a constructor.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p1212code68'); return false;">View Code</a> JAVA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p121268"><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code" id="p1212code68"><pre class="java" style="font-family:monospace;"><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Alist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">List</span></a> aList <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aarraylist+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">ArrayList</span></a><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> aArray <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">5</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>On the first line we created a generic list that can hold ANY type of object, and of any amount of them. On the second line, we created an Array that always has a size of 5, and can only hold Strings. (The type limitation can be seen as a positive or a negative, and we will look at how we can do similar things with Lists when we get to Generics in a different lesson.) </p>
<p>Some of the typical methods of List you will use are :</p>
<p>‚Ä¢ add(Object o) : to add an element to the end of the list<br />
‚Ä¢ add(int index, Object o) : to add an object at a particular index<br />
‚Ä¢ boolean remove(Object o) : remove the specific Object<br />
‚Ä¢ remove(int index) : remove the Object at a particular index<br />
‚Ä¢ boolean contains(Object o) : if an object exists in the list<br />
‚Ä¢ int indexOf(Object o) : position of an index in the list<br />
‚Ä¢ Object get(int index) : return the Object from a particular index<br />
‚Ä¢ Iterator iterator() : return an Iterator for the list<br />
‚Ä¢ size() : number of elements in the list<br />
‚Ä¢ Object[] toArray(Object[] o) : return an Array of type o</p>
<pre lang="Java" name="CollectionsTest1.java" colla="-">
public class CollectionsTest1 {
   public static void main(String[] args) {
      // List is just an interface. We need to create something that
      // implements List, and ArrayList is one such Class that is pretty
      // common, but not the only one.
      List aList1 = new ArrayList();
      aList1.add(new Bird("Tweety"));
      aList1.add(new Fish("Swimmy"));
      aList1.add(new Mammal());
      // Does compiler complain? Does it work at runtime?
      // aList1.add(new String("Johnny"));

      // To prove that our List is a Collection, we have a static method that
      // will print out any item from a Collection
      CollectionUtilities.printAnimalList(aList1);
   }
}
</pre>
<pre lang="Java" name="CollectionUtilities.java" colla="-">
public class CollectionUtilities {

   /**
    * Any object that extends Collection can be printed here. It works because
    * you can get an iterator from a collection object.
    *
    * @param pCollection
    */
   public static void printList(Collection pCollection) {

      for (Iterator iterator = pCollection.iterator(); iterator.hasNext();) {
         Object aObject = iterator.next();
         System.out.println(aObject);
      }
   }

   /**
    * Note that for now, we are only specifying a list, there is nothing to
    * stop you from passing in a list of any type of object. See the generics
    * lesson for more info.
    *
    * @param pAnimalList
    */
   public static void printAnimalList(List pAnimalList) {
      for (Iterator iterator = pAnimalList.iterator(); iterator.hasNext();) {
         // notice the need for a cast
         Animal aAnimal = (Animal) iterator.next();
         System.out.println(aAnimal.getName() + ":" + aAnimal.getType());
      }
   }

   /**
    * Sorts a List of elements of type Animal useing the AnimalComparator
    *
    * @param pAnimalList
    */
   public static void sortAnimals(List pAnimalList) {
      Collections.sort(pAnimalList, new AnimalComparator());
   }

   /**
    * Figured if we had a comparator, we should use it on an array too.
    *
    * @param pAnimalArray
    */
   public static void sortAnimals(Animal[] pAnimalArray) {
      Arrays.sort(pAnimalArray, new AnimalComparator());
   }

   /**
    * Shows how we can take in a list and return a set
    *
    * @param pAnimalList
    * @return
    */
   public static Set findBirds(List pAnimalList) {
      Set aBirdSet = new HashSet();
      for (Iterator iterator = pAnimalList.iterator(); iterator.hasNext();) {
         Animal aAnimal = (Animal) iterator.next();
         if ( aAnimal instanceof Bird ) {
            aBirdSet.add(aAnimal);
         }
      }
      return aBirdSet;
   }
}
</pre>
<p>CollectionsTest1.java is a very basic class that uses an ArrayList. One of powerful features of Java is the use of Interfaces. Using them, we can create methods that know enough to get the job done, but little enough that they are still generic. That is the idea behind CollectionUtilities. The printList method can print anything that is a Collection. The printAnimalList can print more details as long as the item is a List of Animals.</p>
<pre lang="Java" name="CollectionsTest2.java" colla="-">
public class CollectionsTest2 {
   public static void main(String[] args) {
      List aList1 = new ArrayList();
      aList1.add(new Bird("Birdy"));
      // size() method will print number of elements in the list
      System.out.println(aList1.size());
      // clear() method will remove all elements from list
      aList1.clear();
      System.out.println(aList1.size());

      Bird aTweety = new Bird("Tweety");
      aList1.add(aTweety);
      aList1.add(new Fish("Swimmy"));
      aList1.add(new Mammal());

      // contains() method is used to check the list for a particular object
      if (aList1.contains(aTweety)) {
         System.out.println("found tweety");
      } else {
         System.out.println("tweety has flown the coop");
      }
      // remember, this is object equals
      if (aList1.contains(new Fish("Swimmy"))) {
         System.out.println("found swimmy");
      } else {
         System.out.println("swimmy has left the building");
      }

      // get() method to retrieve an object from the list
      Animal aMammal1 = (Animal) aList1.get(2);
      System.out.println("aMammal1(index 2):" + aMammal1.getName());

      // This object is "live". The list only contains pointers to the real
      // objects. Change an object from the list...
      aMammal1.setName("Rover");

      // and the object in the list is changed.
      Animal aMammal2 = (Animal) aList1.get(2);
      System.out.println("aMammal2(index 2):" + aMammal2.getName());
   }
}
</pre>
<p>CollectionsTest2 shows some of the other methods that are commonly used with Lists.</p>
<p>Another interesting thing that is often done with Lists, is to sort them. You can sort Objects in anyway imaginable that makes sense to your for your particular object. One way to do this is to create a reusable class called a Comparator. AnimalComparator is a Comparator that can be used to sort based on first the type, then the name of the Animal. CollectionsTest3 shows how to use this comparator to sort both a List and an Array. This class also shows how you can take a List and turn it into an Array.</p>
<pre lang="Java" name="AnimalComparator.java" colla="-">
/**
 * This Comparator can be used to sort animals. A null animal is < an actual
 * animal. The order is alphabetical on type, then alphabetical on name.
 *
 * Note: not null safe on type and name. If running against VERY large lists you
 * may want to try to avoid creating all the Strings for type and name.
 *
 * @author Chris Ward <veggie2u@cyberward.net>
 */
public class AnimalComparator implements Comparator {
   public int compare(Object pAnimal1, Object pAnimal2) {
      if (pAnimal1 == null &#038;&#038; pAnimal2 == null) {
         return 0; // equal
      }
      if (pAnimal1 == null) {
         return -1; // pAnimal1 < pAnimal2
      }
      if (pAnimal2 == null) {
         return 1; // pAnimal 1 > pAnimal2
      }

      String aType1 = ((Animal) pAnimal1).getType();
      String aType2 = ((Animal) pAnimal2).getType();

      int aTypeCompare = aType1.compareTo(aType2);
      // If different, we don't need to compare anymore
      if (aTypeCompare != 0) {
         return aTypeCompare;
      }

      String aName1 = ((Animal) pAnimal1).getName();
      String aName2 = ((Animal) pAnimal2).getName();
      return aName1.compareTo(aName2);
   }
}
</pre>
<pre lang="Java" name="CollectionsTest3.java" colla="-">
public class CollectionsTest3 {
   public static void main(String[] args) {
      List aList1 = new ArrayList();
      aList1.add(new Bird("Tweety"));
      aList1.add(new Fish("Swimmy"));
      aList1.add(new Mammal());
      aList1.add(new Bird("Robby Robbin"));
      aList1.add(new Mammal("Zeke"));

      System.out.println();
      CollectionUtilities.printAnimalList(aList1);

      // sort using a comparator
      CollectionUtilities.sortAnimals(aList1);

      System.out.println();
      CollectionUtilities.printAnimalList(aList1);

      System.out.println();
      List aList2 = new ArrayList();
      aList2.add(new Bird("Tweety"));
      aList2.add(new Fish("Swimmy"));
      aList2.add(new Mammal());
      aList2.add(new Bird("Robby Robbin"));
      aList2.add(new Mammal("Zeke"));

      // A List can convert to an Array
      Animal[] aAnimalArray = (Animal[]) aList2.toArray(new Animal[0]);

      // You can sort an array with the same comparator
      CollectionUtilities.sortAnimals(aAnimalArray);

      System.out.println();
      for (int i = 0; i < aAnimalArray.length; i++) {
         System.out.println(aAnimalArray[i].getName());
      }
   }
}
</pre>
<h3>Map</h3>
<p>A Map is like a look up table, or index table. For every object that goes into the Map, you have to give an index to where it is. A List can know where each object is by a numeric index, but if you removed the first object, you would no longer know the index of any of the Objects in your list! By using a Map, you can use any type of index you wish. You can use Integers, Strings, or any Object you can come up with. As with List, Map is just an Interface. We will use the HashMap in our examples.</p>
<p>CollectionsTest4 shows how to use a Map and how the concept of keys works. </p>
<pre lang="Java" name="CollectionsTest4.java" colla="-">
public class CollectionsTest4 {
   public static void main(String[] args) {
      Integer aIntegerKey = new Integer(10);

      Map aMap1 = new HashMap();
      aMap1.put("bird", new Bird());
      aMap1.put("fish", new Fish());
      // Notice that there is no restriction on the key type
      aMap1.put(aIntegerKey, new Mammal());

      // Note: Map doesn't actually implement the Collection interface
      // CollectionUtilities.printList(aMap1);

      // A map stores Objects, must cast to Animal
      Animal aBird = (Animal) aMap1.get("bird");
      System.out.println(aBird);

      // Non Strings work as keys just fine
      Mammal aMammal = (Mammal) aMap1.get(aIntegerKey);
      System.out.println(aMammal);
   }
}
</pre>
<p>Some of the more common methods of a Map are:</p>
<p>‚Ä¢ Object put(Object key, Object value)<br />
‚Ä¢ Object get(Object key)<br />
‚Ä¢ boolean containsKey(Object key) : check to see if a particular key exists in the Map<br />
‚Ä¢ boolean containsValue(Object value) : check to see if a particular value exits in the Map<br />
‚Ä¢ Object remove(Object key) : remove the entry that has the particular key<br />
‚Ä¢ int size()</p>
<p>If you get a lot of Birds in a cage, it is tough to remember what bird is inside, so let's use a HashMap to create a cache of Bird objects. BirdCage will use the bird's name as the key, and the actual Bird object as the value. See CollectionsTest5 to see this implemented.</p>
<pre lang="Java" name="BirdCage.java" colla="-">
/**
 * Using a HashMap to implement a type of cache. We use the name of our Bird's
 * as the key. The Bird its self is the value. If the bird does not exist in our
 * cache, we add it. It it is there, we return the one we found.
 *
 * @author Chris Ward <veggie2u@cyberward.net>
 */
public class BirdCage {

   private static BirdCage birdCage;
   private Map birdCache;

   /**
    * The BirdCage is a singleton. We have decided that there will be only one
    * bird cage in per java machine.
    */
   private BirdCage() {
      birdCache = new HashMap();
      System.out.println("Creating a BirdCage. There can be only one bird with a given name.");
   }

   public static BirdCage getInstance() {
      if (birdCage == null) {
         birdCage = new BirdCage();
      }
      return birdCage;
   }

   public Bird checkCage(String pName) {
      if (birdCage == null) {
         getInstance();
      }

      if (!birdCache.containsKey(pName)) {
         System.out.println(pName + " not found... adding.");
         Bird aBird = new Bird(pName);
         birdCache.put(pName, aBird);
         return aBird;
      }
      System.out.println("The name " + pName + " was found");
      System.out.println("Returning original " + pName);
      return (Bird) birdCache.get(pName);
   }

   public int getSize() {
      return birdCache.size();
   }

   public boolean isInCage(String pName) {
      return birdCache.containsKey(pName);
   }
}
</pre>
<pre lang="Java" name="CollectionsTest5.java" colla="-">
public class CollectionsTest5 {
   public static void main(String[] args) {
      BirdCage aCage = BirdCage.getInstance();

      Bird aTweety1 = aCage.checkCage("Tweety");
      Bird aRobby = aCage.checkCage("Robby Robbin");
      //will Tweety be added twice?
      Bird aTweety2 = aCage.checkCage("Tweety");
      Bird aSam = aCage.checkCage("Sam");

      //What will be the size?
      System.out.println("size:" + aCage.getSize());

      //Will these two birds be equal?
      System.out.println("Tweety1 == Tweety2 : " + aTweety1.equals(aTweety2));
      System.out.println("Frank is in cage? " + aCage.isInCage("Frank"));
      System.out.println("Sam is in cage? " + aCage.isInCage("Sam"));
   }
}
</pre>
<h3>Set</h3>
<p>A set is like a partial List. They are often returned from a collection when you have asked for some subset of the whole. For example, if we had a big list of Animals, and we wanted to find out what of these Animals were Birds, we could get a Set back. The methods of Set are much like the List, but with a Set, no two elements are equal within a Set. There are no duplicates.</p>
<p>As an example, take a look at the CollectionsTest6 class. This creates a list, then asks a method from the CollectionUtilities to return a Set of just the Birds.</p>
<pre lang="Java" name="CollectionsTest6.java" colla="-">
public class CollectionsTest6 {
   public static void main(String[] args) {
      List aAnimalList = new ArrayList();
      aAnimalList.add(new Bird("Tweety"));
      aAnimalList.add(new Fish());
      aAnimalList.add(new Mammal());
      aAnimalList.add(new Bird());
      aAnimalList.add(new Bird("Sam"));

      Set aBirdSet = CollectionUtilities.findBirds(aAnimalList);
      CollectionUtilities.printList(aBirdSet);
   }
}
</pre>
<h3>More Information</h3>
<p>Java collections trail: <a href="http://java.sun.com/docs/books/tutorial/collections/index.html">http://java.sun.com/docs/books/tutorial/collections/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/intro-to-java-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<series:name><![CDATA[Intro to Java]]></series:name>
	</item>
		<item>
		<title>Aperture 2 Dodge and Burn</title>
		<link>http://www.cyberward.net/blog/2009/05/aperture-2-dodge-and-burn/</link>
		<comments>http://www.cyberward.net/blog/2009/05/aperture-2-dodge-and-burn/#comments</comments>
		<pubDate>Wed, 27 May 2009 12:00:03 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Aperture]]></category>
		<category><![CDATA[Digital Darkroom]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[aperture]]></category>
		<category><![CDATA[burn]]></category>
		<category><![CDATA[dodge]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1190</guid>
		<description><![CDATA[I am not sure why I was acting to ridiculously. When version 2 came out, I was super psyched, then I found out that if you wanted to use the Dodge and Burn tool, Aperture would make a copy, and send you to the plugin. If you had made any adjustments before this, you couldn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>I am not sure why I was acting to ridiculously. When version 2 came out, I was super psyched, then I found out that if you wanted to use the Dodge and Burn tool, Aperture would make a copy, and send you to the plugin. If you had made any adjustments before this, you couldn&#8217;t tell anymore, all the sliders would look reset. It bugged me that the dodge and burn plug in wasn&#8217;t non destructive. So&#8230; I ignored it.</p>
<p>Just recently I came across an image (can&#8217;t find it now) that was adjusted with this plug-in, and I had a &#8220;what the heck&#8221; kind of moment. I immediately fired up Aperture to re-check out this tool. To get to the plug-in, right click on an image, select Edit With&#8230; and pick Dodge and Burn.</p>
<p><img class="aligncenter size-full wp-image-1191" title="Selecting Dodge and Burn" src="http://www.cyberward.net/blog/wp-content/uploads/aperture1.jpg" alt="Selecting Dodge and Burn" width="500" height="513" /></p>
<p><span id="more-1190"></span>This is an image that I recently worked on. When I look at this image, I want the boat to be the focus. I was trying to take a picture of this tender, just peacefully sitting there, but I need to draw the¬† viewers attention. To do this, I will dodge (lighten) and burn (darken).</p>
<p>The first thing I was going to do is lighten the near side of the boat. Pay attention to the sliders at the top. First select Dodge, and select a tool from Pen, Eraser, and Feather. Lets start with the Pen. Then pick a size. Don&#8217;t be afraid to pick a very large size if you are doing a larger area. It make it quicker, and helps reduce uneven lighting. The softness slider is important. All the way to the right, the brush is very soft, and will create very gradual transitions. This is usually the most realistic way to do this. All the way to the left and the edge is a very hard edge. I will often do that with the Eraser. Soft brush to lighten, and if I went past an edge, I will switch to a hard edge to back up a bit. Now select a strength. You can experiment with this. Usually I find you want a lighter touch, and to apply several brush strokes.</p>
<p><img class="aligncenter size-full wp-image-1192" title="Dodging the boat" src="http://www.cyberward.net/blog/wp-content/uploads/aperture2.jpg" alt="Dodging the boat" width="500" height="377" /></p>
<p>So the above image is showing the side of the boat getting burned in a bit. You can see with a soft brush that the light appears pretty nicely. And remember, if you go over where you wanted to paint in with light, you can use the eraser. If you catch what I am saying, while you are in the plug-in, the tool is non-destructive. You can apply and erase light all you want. Sweet. What if you are unsure where you applied the light. Look to the far right drop down. Select &#8220;Show Dodge as Overlay&#8221;.</p>
<p><img class="aligncenter size-full wp-image-1193" title="Overlay" src="http://www.cyberward.net/blog/wp-content/uploads/aperture3.jpg" alt="Overlay" width="500" height="377" /></p>
<p>You can see that the window goes grey, and the parts of the image that have light applied show up in red. This can be really helpful, especially when you are using the eraser.</p>
<p>Now, lightening isn&#8217;t the only way to draw a viewers attention. You can also darken everything else, or just parts to direct attention. For this image, I darkened the dock and the top of the sky. Remember that thing about non-destructive editing when dodging, well you can switch back and forth from any of the the different effects you want to apply. There is more than Dodge and Burn to this tool. You can also do saturation, sharpening, contrast, and others. Experiment with the tool to see what works. I find that selective sharpening is also a great use of the tool.</p>
<p>Because this tool creates a new image, I find it¬† best to do early on, even first before doing anything else. Then the normal tools will make more sense when you get back to the normal editing environment. Your image will have a little dot within a circle to indicate a image copy was made. This happens with all plug-ins and when sending the image to Photoshop.</p>
<p>Here is the final image after applying some dodging to the boat, burning to the dock and upper sky, and sharpening to the boat edges. In this case the changes are fairly subtle, but that is what I thought was appropriate.</p>
<p><a class="tt-flickr tt-flickr-Medium" title="Peaceful Tender at Night" href="http://www.flickr.com/photos/v3ggi32u/3565765292/"><img class="alignnone" src="http://farm4.static.flickr.com/3630/3565765292_3d49caebd8.jpg" alt="Peaceful Tender at Night" width="500" height="334" /></a></p>
<p>So I have changed my mind. I find this to be a very useful tool now. I still think that it is unfortunate that a new raster image has to be created every time you use this tool, so I would advise trying to avoid going in and out of this tool. Try to get it all corrected and saved once.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/aperture-2-dodge-and-burn/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing Zenphoto on 1and1</title>
		<link>http://www.cyberward.net/blog/2009/05/installing-zenphoto-on-1and1/</link>
		<comments>http://www.cyberward.net/blog/2009/05/installing-zenphoto-on-1and1/#comments</comments>
		<pubDate>Wed, 13 May 2009 01:45:57 +0000</pubDate>
		<dc:creator>Chris Ward</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[zenphoto]]></category>

		<guid isPermaLink="false">http://www.cyberward.net/blog/?p=1132</guid>
		<description><![CDATA[
I had all kinds of trouble getting Zenphoto to install on 1and1. None of which I believe are the fault of the Zenphoto project. I am blaming the difficulties on how you need to configure php on 1and1.
What problems did I have. It appears that there were tables that were not created correctly. The way [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-1133" title="zen-logo" src="http://www.cyberward.net/blog/wp-content/uploads/zen-logo.gif" alt="zen-logo" width="200" height="47" /></p>
<p>I had all kinds of trouble getting <a href="http://www.zenphoto.org">Zenphoto</a> to install on 1and1. None of which I believe are the fault of the Zenphoto project. I am blaming the difficulties on how you need to configure php on 1and1.</p>
<p>What problems did I have. It appears that there were tables that were not created correctly. The way I figured this out was that I was trying to save a ¬†guest user and password to¬†and album. The name wouldn&#8217;t stick. When I went in and look under the MySql admin¬†tool (phpMyAdmin), there was no user field in the albums table. Something was wrong right from setup.</p>
<p>So here are the steps that I came up with to get zenphoto installed properly. I can&#8217;t say that all of the steps I took were necessary, and some might even be suspect, but in total it works.</p>
<p><span id="more-1132"></span></p>
<p>First of all, I am on a linux hosted shared server on 1and1. That is important, because of how php must be configured. The commands here need to be entered at the command line. You can ssh here, or use putty from windows, but this is not an explanation on how to do that.</p>
<p>I downloaded the current version which at this point is zenphoto-1.2.4.tar.gz.¬†To do this I used wget so I don&#8217;t need to transfer it after downloading. Then I expanded the archive and installed the files.</p>
<pre>wget http://zenphoto.googlecode.com/files/zenphoto-1.2.4.tar.gz
tar -xvzf zenphoto-1.2.4.tar.gz</pre>
<p>Don&#8217;t do the setup yet.</p>
<p>I then went to the 1and1 web site, logged in and went to the MySQL Administration control panel. I selected to create a new database, and picked version 6. You can choose between 5 and 6. I picked 6. 1and1 will tell you the user name, password, host, and database name you will need to enter into setup, but don&#8217;t run setup yet.</p>
<p>We want to tell apache to use PHP5 instead of 4. To do this we want to modify the .htaccess file that comes with zenphoto. In that file are some rules for rewriteing. We don&#8217;t want to change those. Just add a couple of lines. To edit this file I typed</p>
<pre>nano -w .htaccess</pre>
<p>You need to add these two lines after the comment lines (with #&#8217;s) and before the &lt;IfModule mod_rewrite.c&gt; line</p>
<pre>AddType xmapp-php5 .php
AddHandler x-mapp-php5 .php</pre>
<p>Now that is done press ctrl-X to exit, and say yes to saving. Don&#8217;t run set up yet. We have a couple more things to do.</p>
<p>Now we need to tell php to turn off magic quotes, and to use UTF character encoding. We do this by creating a php.ini file in the directory where the code is. This is the dumb part. You need this in every directory you have php code. I put it in the root of my zenphoto install, and in the zp-core folder. This is what I put there.</p>
<pre>[PHP]
magic_quotes_gpc = Off
mbstring.internal_encoding = UTF-8</pre>
<p>If you want to create this file, type</p>
<pre>nano -w php.ini</pre>
<p>Now copy the code above and press shift-insert in the terminal window. Then you can press ctrl-X and say yes to save.</p>
<p>I also copied this file to the zp-core folder</p>
<pre>cp php.ini zp-core/</pre>
<blockquote><p>Just a note: There are instructions on the web that you can add these directives to your .htaccess file, but that will not work on 1and1 linux shared hosting. You will get a 500 server error. See <a href="http://faq.1and1.com/scripting_languages_supported/php/14.html">here</a>.</p></blockquote>
<p>Ok, now you can run setup. Go to your browser and head to http://www.yourwebsite/zenphoto/ This will in turn tack the zp-core/setup.php to the end and start the setup. There will be a couple of warnings left. First one is about strict permissions. I clicked on the link, and zenphoto set things up how it wanted. Next is the .htaccess file. Ignore this one, because we modified the file. The time stamp should be different.</p>
<p>Now you can go ahead and enter you database information. Press OK, and zenphoto should tell you that everything is A OK. You will then set up an Admin user and password, then you are given the opportunity to log in.</p>
<p>If you want to check out the issue I had, upload some files to a new album. Then edit the album and put in a guest user and password and save. Log out, then click on the album you created and locked. Enter the name and password you entered for the guest user. If when you login you can see the album, you are good to go. When I did this process before this procedure, I would try to save the album with the guest user. The name would disappear once I pressed save. Then when I tried to log in I was given an error.</p>
<p>I hope that saves someone some hassles. Good luck.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cyberward.net/blog/2009/05/installing-zenphoto-on-1and1/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
