package de.memtext.baseobjects.coll; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import de.memtext.baseobjects.NamedObjectI; import de.memtext.util.EqualsUtil; import de.memtext.util.StringUtils; /** * * @author MB * */ public class NamedObjectCollection extends BaseObjectCollection implements Collection, Serializable { private static final long serialVersionUID = 1; public NamedObjectCollection() { super(); } /** * Tries to find an element with the given name * @param name * @return first element with given name * @throws IllegalArgumentException if nothing found */ public NamedObjectI getByName(String name) { NamedObjectI test, result = null; for (Iterator it = collect.iterator(); it.hasNext();) { test = (NamedObjectI) it.next(); if (test.getName().equals(name)) { result = test; break; } } if (result == null) throw new IllegalArgumentException("No element with name " + name + " found."); return result; } /** * like '12','34','343' * useful for creating sqls like where x in (...) * @return '' if collection is empty */ public String getNamesApostropheString() { StringBuffer result = new StringBuffer(); NamedObjectI test; for (Iterator it = collect.iterator(); it.hasNext();) { test = (NamedObjectI) it.next(); result.append("'" + test.getName() + "',"); } StringUtils.deleteLastChar(result); if (result.length() == 0) result.append("''"); return result.toString(); } public boolean containsItemWithName(String name) { boolean result = false; NamedObjectI test; for (Iterator it = collect.iterator(); it.hasNext();) { test = (NamedObjectI) it.next(); if (EqualsUtil.areEqual(test.getName(), name)) { result = true; break; } } return result; } @Override public boolean add(Object o) { if (o == null) throw new IllegalArgumentException("can't add null value"); if (!(o instanceof NamedObjectI)) throw new IllegalArgumentException("only named Objects allowed"); return collect.add(o); } @Override public String toString() { StringBuffer result = new StringBuffer(size() + " NamedObjects: "); for (Iterator it = this.iterator(); it.hasNext();) { NamedObjectI element = (NamedObjectI) it.next(); result.append(element + " - "); } return result.toString(); } /** * Only shallow copy */ @Override protected Object clone() throws CloneNotSupportedException { NamedObjectCollection c = new NamedObjectCollection(); c.addAll(this); return c; } }