/* * Moonlight|3D Copyright (C) 2005 The Moonlight|3D team * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Created on Nov 6, 2005 */ package ml.core.helper; import java.util.ArrayList; import java.util.List; /** * This class implements a pool of named objects. It can check if a given * name is unique or it can generate a unique name from the given name. * * @see ml.core.helper.NamedObject * * @author gregor */ public class NamePool implements Cloneable { private ArrayList namedObjects; public NamePool() { namedObjects = new ArrayList(); } @Override public NamePool clone() { NamePool copy=new NamePool(); copy.namedObjects=(ArrayList) namedObjects.clone(); return copy; } /** * Clear the name pool. */ public void clear() { namedObjects.clear(); } /** * Add an object to the name pool. * * @param object the object to add. */ public void add(NamedObject object) { namedObjects.add(object); } /** * Remove an object from the name pool. * * @param object the object to remove */ public void remove(NamedObject object) { for (int i = 0; i < namedObjects.size(); i++) { if (namedObjects.get(i) == object) { namedObjects.remove(i); break; } } } /** * Get a list of all objects in the pool. * * @return list of all objects in the pool */ public List getPooledObjects() { return (ArrayList) namedObjects.clone(); } /** * Check if the given name already occurs in the pool. * * @param name the name to check for * @return true if the name is does not already occur, false otherwise */ public boolean isNameUnique(String name) { for (int i = 0; i < namedObjects.size(); i++) { if (namedObjects.get(i).getName().equals(name)) { return false; } } return true; } /** * Generate a unique name from the given name. The given name is used * as a base name. If it collides with a name in the pool, a number is * appended to make it unique. * * @param baseName the base name to use * @return a unique name based on the base name */ public String generateUniqueName(String baseName) { if (isNameUnique(baseName)) { return baseName; } int i = 1; while (true) { String buffer = baseName + i; if (isNameUnique(buffer)) { return buffer; } i++; } } }