KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jdesktop > dataset > NameGenerator


1 /*
2  * $Id: NameGenerator.java,v 1.1 2005/02/23 17:51:32 rbair Exp $
3  *
4  * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
5  * Santa Clara, California 95054, U.S.A. All rights reserved.
6  */

7
8 package org.jdesktop.dataset;
9 import java.util.Map JavaDoc;
10 import java.util.WeakHashMap JavaDoc;
11
12 /**
13  * Generates names. Give it a prefix, it adds a postfix. Ask it to clear out
14  * a name when it is no longer used, so that it can reuse that name
15  *
16  * @author rbair
17  */

18 class NameGenerator {
19     private String JavaDoc prefix;
20     private Map JavaDoc<Object JavaDoc,String JavaDoc> usedNames = new WeakHashMap JavaDoc<Object JavaDoc,String JavaDoc>();
21     
22     /** Creates a new instance of NameGenerator */
23     public NameGenerator(String JavaDoc prefix) {
24         this.prefix = prefix;
25     }
26     
27     /**
28      * Generates a new name based on the prefix. The object reference is used
29      * to associate with the generated name. The object reference is kept in a
30      * weak reference, so that when this object retains the last reference to
31      * obj, the generated name can be removed automatically
32      */

33     public String JavaDoc generateName(Object JavaDoc obj) {
34         for (int i=0; i<Integer.MAX_VALUE; i++) {
35             String JavaDoc name = prefix + (i+1);
36             if (!usedNames.values().contains(name)) {
37                 usedNames.put(obj, name);
38                 return name;
39             }
40         }
41         assert false : "Apparently I ran out of available names, this should never happen";
42         return null;
43     }
44 }
45
Popular Tags