import java.util.*; /** * CharBag.java * * * Created: Mon Jan 20 13:03:08 2003 * *
A bag of characters,
* i.e., an unordered collection of characters,
* that may contain some character some number of times.
*
* @author Stuart C. Shapiro
*/
public class CharBag extends AbstractCollection {
/**
* The real object, for which this CharBag
is a proxy object.
*/
private StringBuffer chars;
/**
* Creates a new empty CharBag
instance.
*
*/
public CharBag (){
super();
chars = new StringBuffer();
}
/**
* Creates a new CharBag
instance
* containing all the chars of b
.
*
* @param b a StringBuffer
value
*/
public CharBag (StringBuffer b) {
this();
chars.append(b);
}
/**
* Adds c
to this bag of characters.
*
* @param c a char
value
* @return true
*/
public boolean add(char c) {
chars.append(c);
return true;
}
/**
* Returns the index of c
in the chars of this bag, or -1.
*
* @param c a char
value
* @return the index of c
, if it is in this bag of characters;
* otherwise, -1
*/
private int indexOf(char c) {
return chars.indexOf("" + c);
}
/**
* Removes char
from this bag of characters.
*
* post: this == this@pre->excluding(c)
*
* @param c a char
value
* @return true
if c
was in this@pre;
* false
otherwise
*/
public boolean remove(char c) {
int i = indexOf(c);
if (i < 0) {return false;}
chars.deleteCharAt(i);
return true;
}
/**
* Tests if c
is in this bag of characters.
*
* @param c a char
value
* @return true
if this->includes(c), else false
*/
public boolean contains(char c) {
return indexOf(c) >= 0;
}
/**
* Tests if this bag of characters is empty
*
* @return true
if this is empty, else false
*/
public boolean isEmpty() {
return chars.length() == 0;
}
/**
* Returns the number of characters in this bag of characters.
*
* @return the number of characters in this bag of characters.
*/
public int size() {
return chars.length();
}
/**
* Tests whether this bag and b
have the same characters
* the same number of times.
*
* @param b a CharBag
value
* @return true
* if this bag and b
have the same characters
* the same number of times.
* else false
*/
public boolean equals(CharBag b) {
if (size() != b.size()) {return false;}
CharBag tmp = new CharBag(b.chars);
for (int i=0; i