Skip to content

Instantly share code, notes, and snippets.

@coffeejay
Created January 15, 2014 15:45
Show Gist options
  • Save coffeejay/8438560 to your computer and use it in GitHub Desktop.
Save coffeejay/8438560 to your computer and use it in GitHub Desktop.
/**
* A class representation of a Bag type using ArrayList
* which implements BagInterface.
*
* @author Jay Deuskar
*/
import java.util.ArrayList;
public class ArrayListBag<T> implements BagInterface<T>{
private ArrayList<T> bag;
public int currentSize;
public ArrayListBag(){
currentSize = 0;
bag = new ArrayList<T>();
}
public int getCurrentSize(){
return bag.size();
}
public boolean isEmpty(){
if (this.getCurrentSize() == 0)
return true;
else
return false;
}
public boolean add(T newEntry){
if (newEntry != null){
bag.add(newEntry);
currentSize++;
return true;
}
else
return false;
}
public T remove(){
if (currentSize!=0)
{
int range = (int)Math.random() * currentSize;
T objectToRemove = bag.get(range);
bag.remove(range);
currentSize--;
return objectToRemove;
}
else
return null;
}
public boolean remove(T anEntry){
if (bag.contains(anEntry)){
bag.remove(anEntry);
currentSize--;
return true;
}
else
return false;
}
public void clear(){
bag.clear();
}
public int getFrequencyOf(T anEntry){
int counter = 0;
for (int i = 0; i < this.getCurrentSize(); i++){
if (anEntry.equals(bag.get(i))){
counter++;
}
}
return counter;
}
public boolean contains(T anEntry){
int counter = 0;
for (T entry: this.toArray()){
if (entry.equals(anEntry))
counter++;
}
if (counter>0)
return true;
else
return false;
}
public T[] toArray(){
return (T[])bag.toArray(new Object[this.getCurrentSize()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment