Need help in my "Custom Set" implementation - java

Okay I have a really annoying error. Its coming from my retainAll method. The problem is that I am outputting 1,3,5 in ints at the end, but I need 1,3,5,7,9. Here is the code below for the MySet and driver classes
public class MySetTester {
public static void main(String[]args) {
MySet<String> strings = new MySet<String>();
strings.add("Hey!");
strings.add("Hey!");
strings.add("Hey!");
strings.add("Hey!");
strings.add("Hey!");
strings.add("Listen!");
strings.add("Listen!");
strings.add("Sorry, I couldn't resist.");
strings.add("Sorry, I couldn't resist.");
strings.add("(you know you would if you could)");
System.out.println("Testing add:\n");
System.out.println("Your size: " + strings.size()
+ ", contains(Sorry): " + strings.contains("Sorry, I couldn't resist."));
System.out.println("Exp. size: 4, contains(Sorry): true\n");
MySet<String> moreStrings = new MySet<String>();
moreStrings.add("Sorry, I couldn't resist.");
moreStrings.add("(you know you would if you could)");
strings.removeAll(moreStrings);
System.out.println("Testing remove and removeAll:\n");
System.out.println("Your size: " + strings.size()
+ ", contains(Sorry): "
+ strings.contains("Sorry, I couldn't resist."));
System.out.println("Exp. size: 2, contains(Sorry): false\n");
MySet<Integer> ints = new MySet<Integer>();
for (int i = 0; i < 100; i++) {
ints.add(i);
}
System.out.println("Your size: " + ints.size());
System.out.println("Exp. size: 100\n");
for (int i = 0; i < 100; i += 2) {
ints.remove(i);
}
System.out.println("Your size: " + ints.size());
System.out.println("Exp. size: 50\n");
MySet<Integer> zeroThroughNine = new MySet<Integer>();
for (int i = 0; i < 10; i++) {
zeroThroughNine.add(i);
}
ints.retainAll(zeroThroughNine);
System.out.println("ints should now only retain odd numbers"
+ " 0 through 10\n");
System.out.println("Testing your iterator:\n");
for (Integer i : ints) {
System.out.println(i);
}
System.out.println("\nExpected: \n\n1 \n3 \n5 \n7 \n9\n");
System.out.println("Yours:");
for (String s : strings) {
System.out.println(s);
}
System.out.println("\nExpected: \nHey! \nListen!");
strings.clear();
System.out.println("\nClearing your set...\n");
System.out.println("Your set is empty: " + strings.isEmpty());
System.out.println("Exp. set is empty: true");
}
}
And here is the main code. But still read the top part because that's where my examples are.
import java.util.Set;
import java.util.Collection;
import java.lang.Iterable;
import java.util.Iterator;
import java.util.Arrays;
import java.lang.reflect.Array;
public class MySet<E> implements Set<E>, Iterable<E>
{
// instance variables - replace the example below with your own
private E[] backingArray;
private int numElements;
/**
* Constructor for objects of class MySet
*/
public MySet()
{
backingArray=(E[]) new Object[5];
numElements=0;
}
public boolean add(E e){
for(Object elem:backingArray){
if (elem==null ? e==null : elem.equals(e)){
return false;
}
}
if(numElements==backingArray.length){
E[] newArray=Arrays.copyOf(backingArray,backingArray.length*2);
newArray[numElements]=e;
numElements=numElements+1;
backingArray=newArray;
return true;
}
else{
backingArray[numElements]=e;
numElements=numElements+1;
return true;
}
}
public boolean addAll(Collection<? extends E> c){
for(E elem:c){
this.add(elem);
}
return true;
}
public void clear(){
E[] newArray=(E[])new Object[backingArray.length];
numElements=0;
backingArray=newArray;
}
public boolean equals(Object o){
if(o instanceof Set &&(((Set)o).size()==numElements)){
for(E elem:(Set<E>)o){
if (this.contains(o)==false){
return false;
}
return true;
}
}
return false;
}
public boolean contains(Object o){
for(E backingElem:backingArray){
if (o!=null && o.equals(backingElem)){
return true;
}
}
return false;
}
public boolean containsAll(Collection<?> c){
for(E elem:(Set<E>)c){
if(!(this.contains(elem))){
return false;
}
}
return true;
}
public int hashCode(){
int sum=0;
for(E elem:backingArray){
if(elem!=null){
sum=sum+elem.hashCode();
}
}
return sum;
}
public boolean isEmpty(){
if(numElements==0){
return true;
}
else{
return false;
}
}
public boolean remove(Object o){
int i=0;
for(Object elem:backingArray){
if(o!=null && o.equals(elem)){
backingArray[i]=null;
numElements=numElements-1;
E[] newArray=Arrays.copyOf(backingArray,backingArray.length-1);
return true;
}
i=i+1;
}
return false;
}
public boolean removeAll(Collection<?> c){
for(Object elem:c){
this.remove(elem);
}
return true;
}
public boolean retainAll(Collection<?> c){
MySet<E> removalArray=new MySet<E>();
for(E arrayElem:backingArray){
if(arrayElem!= null && !(c.contains(arrayElem))){
this.remove(arrayElem);
}
}
return false;
}
public int size(){
return numElements;
}
public <T> T[] toArray(T[] a) throws ArrayStoreException,NullPointerException{
for(int i=0;i<numElements;i++){
a[i]=(T)backingArray[i];
}
for(int j=numElements;j<a.length;j++){
a[j]=null;
}
return a;
}
public Object[] toArray(){
Object[] newArray=new Object[numElements];
for(int i=0;i<numElements;i++){
newArray[i]=backingArray[i];
}
return newArray;
}
public Iterator<E> iterator(){
setIterator iterator=new setIterator();
return iterator;
}
private class setIterator implements Iterator<E>{
private int currIndex;
private E lastElement;
public setIterator(){
currIndex=0;
lastElement=null;
}
public boolean hasNext(){
while(currIndex<=numElements && backingArray[currIndex]==null){
currIndex=currIndex+1;
}
if (currIndex<=numElements){
return true;
}
return false;
}
public E next(){
E element=backingArray[currIndex];
currIndex=currIndex+1;
lastElement=element;
return element;
}
public void remove() throws UnsupportedOperationException,IllegalStateException{
if(lastElement!=null){
MySet.this.remove((Object)lastElement);
numElements=numElements-1;
}
else{
throw new IllegalStateException();
}
}
}
}
I've been able to reduce the problems, but otherwise this thing is still causing problems.

Bug in the remove method. I added my implementation this method:
public boolean remove(Object o) {
int i = 0;
for (Object elem : backingArray) {
if (o != null && o.equals(elem)) {
System.arraycopy(backingArray, i+1, backingArray, i, numElements-i-1);
backingArray[numElements-1] = null;
numElements = numElements - 1;
return true;
}
i = i + 1;
}
return false;
}
and another bug in method retainAll. I added my implementation this method:
public boolean retainAll(Collection<?> c) {
int index = 0;
boolean result = false;
if (this.containsAll(c)){
result = true;
}
while(index < numElements) {
E e = backingArray[index];
if (e != null && !(c.contains(e))) {
this.remove(e);
} else {
index++;
}
}
return result;
}

Question is answered #frostjogla. Adding one more. If you've checked the actual content of backingArray each time, you could have noticed the issue earlier.
You can do it by overwriting the toString method like
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (E backingElem : backingArray) {
sb.append(" ").append(backingElem);
}
return sb.toString();
}
and print by
System.out.println("Contents of MySet " + ints);

Related

How to create a vector that implements the Map interface?

I need to create a vector class that implements the Map interface, but in the put method it returns NullException, I need help implementing the put method, I can't find this type of content on the internet
public class Vetor_map implements Map<Key, Student> {
private int nElements;
private Map<Key, Student> mapa[];
public Vetor_map(int max) {
mapa = new Map[max];
nElements = 0;
}
// PUT
#Override
public Estudante put(Key key, Estudants value) {
if (!isFull()) {
mapa[nElements].put(key, value);
nElements++;
return value;
}
return value;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
if (nElements == 0)
return true;
return false;
}
public boolean isFull() {
if (nElements == mapa.length) {
return true;
}
return false;
}
Class main:
public static void main(String[] args) {
// TODO Auto-generated method stub
Key ch = new Key();
Student es = new Student();
Vetor_map vm = new Vetor_map(10);
System.out.println("Key: " + ch + ", Estudant: "+ es);
vm.put(ch, es);
Error
A Map is a collection of entries where each entry is a key-value pair. So your Vetor_map class should implement java.util.Map – which it does – but I think that you should also create a class that implements interface Map.Entry.
In the below code, I added an inner class VectorMapEntry that implements Map.Entry and therefore class VectorMap – which implements interface Map – contains an array of VectorMapEntry instances. From there it is just a simple matter of implementing the methods of both interfaces, namely Map and Map.Entry.
Note the following in the below code.
I changed the name from Vetor_map to VectorMap.
I added methods toString() and main() to class VectorMap for testing purposes only. I also added method toString() to classes Key and Student also for testing purposes.
You did not supply code for classes Key and Student so I added skeleton definitions for those two classes. Note that each class – Key and Student – must each implement method equals. I only added method hashCode since the javadoc for method equals() recommends doing so.
VectorMap cannot contain a null Key but it can contain a null Student as a value for a given Key.
Each Key in VectorMap is unique. When calling method put() with a Key that already exists in VectorMap, the existing value is replaced.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class VectorMap implements Map<Key, Student> {
private static class VectorMapEntry implements Map.Entry<Key, Student> {
private Key key;
private Student student;
public VectorMapEntry(Key k, Student s) {
key = k;
student = s;
}
public Key getKey() {
return key;
}
public Student getStudent() {
return student;
}
public void setStudent(Student s) {
student = s;
}
#Override
public Student getValue() {
return student;
}
#Override
public Student setValue(Student value) {
student = value;
return value;
}
}
private int nElements;
private VectorMapEntry[] entries;
public VectorMap(int initialSize) {
if (initialSize <= 0) {
throw new IllegalArgumentException("Initial size must be positive.");
}
entries = new VectorMapEntry[initialSize];
}
#Override
public int size() {
return nElements;
}
#Override
public boolean isEmpty() {
return nElements == 0;
}
#Override
public boolean containsKey(Object key) {
boolean found = false;
for (VectorMapEntry entry : entries) {
if (entry == null) {
break;
}
found = entry.getKey().equals(key);
if (found) {
break;
}
}
return found;
}
#Override
public boolean containsValue(Object value) {
boolean found = false;
for (VectorMapEntry entry : entries) {
if (entry == null) {
break;
}
found = entry.getStudent().equals(value);
if (found) {
break;
}
}
return found;
}
#Override
public Student get(Object key) {
for (VectorMapEntry entry : entries) {
if (entry == null) {
break;
}
if (entry.getKey().equals(key)) {
return entry.getStudent();
}
}
return null;
}
#Override
public Student put(Key key, Student value) {
if (key == null) {
throw new IllegalArgumentException("Null key.");
}
boolean found = false;
for (VectorMapEntry entry : entries) {
if (entry == null) {
break;
}
if (entry.getKey().equals(key)) {
entry.setStudent(value);
found = true;
break;
}
}
if (!found) {
if (nElements == entries.length) {
throw new RuntimeException("Map is full.");
}
entries[nElements] = new VectorMapEntry(key, value);
nElements++;
}
return value;
}
#Override
public Student remove(Object key) {
int index = 0;
Student s = null;
for (VectorMapEntry entry : entries) {
if (entry == null) {
break;
}
if (entry.getKey().equals(key)) {
s = entry.getStudent();
break;
}
index++;
}
if (index < nElements) {
for (int i = index; i < nElements - 1; i++) {
entries[i] = entries[i + 1];
}
nElements--;
}
return s;
}
#Override
public void putAll(Map<? extends Key, ? extends Student> m) {
if (m != null) {
m.entrySet()
.stream()
.forEach(ent -> put(ent.getKey(), ent.getValue()));
}
}
#Override
public void clear() {
for (int i = 0; i < nElements; i++) {
entries[i] = null;
}
nElements = 0;
}
#Override
public Set<Key> keySet() {
Set<Key> keySet = new HashSet<>();
for (int i = 0; i < nElements; i++) {
keySet.add(entries[i].getKey());
}
return keySet;
}
#Override
public Collection<Student> values() {
Collection<Student> vals = new ArrayList<>(nElements);
for (int i = 0; i < nElements; i++) {
vals.add(entries[i].getStudent());
}
return vals;
}
#Override
public Set<Map.Entry<Key, Student>> entrySet() {
Set<Map.Entry<Key, Student>> entSet = new HashSet<>();
for (int i = 0; i < nElements; i++) {
entSet.add(entries[i]);
}
return entSet;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
boolean first = true;
for (int i = 0; i < nElements; i++) {
if (first) {
first = false;
}
else {
sb.append(", ");
}
sb.append(entries[i].getKey());
sb.append('=');
sb.append(entries[i].getValue());
}
sb.append(']');
return sb.toString();
}
public static void main(String[] args) {
Key ch = new Key();
Student es = new Student();
VectorMap vm = new VectorMap(10);
System.out.println("Key: " + ch + ", Estudant: "+ es);
vm.put(ch, es);
System.out.println(vm);
}
}
class Key {
public boolean equals(Object obj) {
return false;
}
public int hashCode() {
return -1;
}
public String toString() {
return "Key";
}
}
class Student {
public boolean equals(Object obj) {
return false;
}
public int hashCode() {
return -1;
}
public String toString() {
return "Student";
}
}
Also note that it would be possible to change the above code such that VectorMap could (theoretically) contain an infinite number of key-value pairs. This could be achieved by simply enlarging the entries array whenever it gets completely filled.

Java - TreeMap do not retrieves the key

I've topped with a problem I can not understand exactly what's happening here.
I operate with a TreeMap<Custom_class, TreeMap<Custom_class, Integer>>
Here is the fragment of code:
TreeMap<Coordenada, Integer> helper_tree;
boolean newLine = false;
for (Linea l : this.lineas) {
int helper = 0;
newLine = true;
Coordenada helper_co = null;
for (Coordenada c : l.getNodosLinea()) {
helper++;
if (!c.getEsEstacion() && !c.getEsCruce()) continue;
if (newLine) { map.putIfAbsent(c, new TreeMap<>()); helper_co = c; helper = 0; newLine = false; continue; }
helper_tree = new TreeMap<>();
helper_tree.put(helper_co, helper * 200);
map.put(c, helper_tree);
map.get(helper_co).put(c, helper * 200);
helper_co = c;
helper = 0;
}
}
In the execution the highlighted line fails, getting 0 entry for a key:
debug mode in intellij
And this is TreeMap structure:
TreeMap structure
I dont understand why in fails at .get(key) when the key Coordenada(12,2) is present. All before works just fine.
Coordenada class
public class Coordenada implements Comparable<Coordenada>{
private int[] coordenada = new int[2];
private boolean esEstacion = false;
private boolean esCruce = false;
public Coordenada(int[] coordenada){
this.coordenada[0] = coordenada[0];
this.coordenada[1] = coordenada[1];
}
public void setCoordenada(int[] coordenada) {
this.coordenada = coordenada;
}
public int[] getCoordenada() {
return coordenada;
}
public void switchEstacion(){
this.esEstacion = !this.esEstacion;
}
public void switchCruce() { this.esCruce = !this.esCruce; }
public boolean getEsEstacion() {
return this.esEstacion;
}
public boolean getEsCruce() { return this.esCruce; }
#Override
public boolean equals(Object coord){
Coordenada coordTemp = (Coordenada) coord;
if (this.coordenada[0] != coordTemp.coordenada[0])
return false;
if (this.coordenada[1] != coordTemp.coordenada[1])
return false;
return true;
}
#Override
public int compareTo(Coordenada o) {
if (this.coordenada[0] > o.coordenada[0] )
return 1;
if (this.coordenada[1] > o.coordenada[1] )
return 1;
if (this.coordenada[0] < o.coordenada[0])
return -1;
if (this.coordenada[1] < o.coordenada[1])
return -1;
return 0;
}
#Override
public String toString() {
return "(" + coordenada[0] + ", " + coordenada[1] + ")";
}
}
Inserts perfectly Coordenada(12,2) and modifies previous helper_co = Coordenada(10,2)
debugger variables
Thanks for any help!
Look at your compareTo function
(0,1) compareTo (1,0) returns 1
(1,0) compareTo (0,1) returns 1
It's ambiguous.

Generic Array Method Class in Java

I've been trying to turn this generic arraylist class into an array but I haven't been able to get it to work. I've hit a roadblock at the push() and pop() methods. Any help is appreciated.
Here's the original class:
public class GenericStack<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public E push(E o) {
list.add(o);
return o;
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
}
And here's my revised class so far:
public class GenericStack<E> {
public static int size = 16;
#SuppressWarnings("unchecked")
private E[] list = (E[])new Object[size];
public void add(int index, E e) {
ensureCapacity();
for (int i = size - 1; i >= index; i--) {
list[i + 1] = list[i];
list[index] = e;
size++;
}
}
public int getLength() {
return list.length;
}
public E peek() {
E o = null;
o = list[0];
return o;
}
public E push(E o) {
ensureCapacity();
list.append(o);
size++;
return o;
}
public E pop() {
E o = null;
for (int i = 0; i > list.length; i++) {
o = list[i - 1];
}
list[list.length - 1] = null;
size--;
return o;
}
private void ensureCapacity() {
if (size >= list.length) {
#SuppressWarnings("unchecked")
E[] newlist = (E[])(new Object[size * 2 + 1]);
System.arraycopy(list, 0, newlist, 0, size);
list = newlist;
}
}
public boolean isEmpty() {
if (list.length > 0) {
return false;
}
else {
return true;
}
}
}
NB: You must first correct your code like mentioned in comments.
It's recommended to use name method like of official Stack class, so there are 5 methods: empty() peek() pop() push(E item) search(Object o).
You should declare initial size of your array as a constant and an other variable for current size and all your attributes should be private like that:
private final int MAX_SIZE = 16;
private int currentSize=0;
There is the code of peek() method:
public E peek() {
E o = null;
o = list[currentSize-1];
return o;
}
There is the code of push(E o) method:
public E push(E o) {
list[currentSize]=o;
currentSize++;
return o;
}
There is the code of pop() method this method must throw EmptyStackException - if this stack is empty:
public E pop() {
E o = null;
if(currentSize>0){
o=list[currentSize - 1];
list[currentSize - 1] = null;
currentSize--;
return o;
}else{
throw new EmptyStackException();
}
}
There is the code of empty() method:
public boolean empty() {
if (currentSize > 0) {
return false;
}
else {
return true;
}
}

adding an iterator to my arraylist

import java.util.Iterator;
public class MyArrayList<E> implements Iterable<E> {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
public MyArrayList() {
size = 0;
capacity = DEFAULT_SIZE;
items = new Object[DEFAULT_SIZE];
}
private void expand() {
Object[] newItems = new Object[capacity + EXPANSION];
for (int j = 0; j < size; j++) newItems[j] = items[j];
items = newItems;
capacity = capacity + EXPANSION;
}
public void add(Object obj) {
if (size >= capacity) this.expand();
items[size] = obj;
size++;
}
public int size() {
return size;
}
public Object get(int index) {
try{
return items[index];
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}
public boolean contains(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return true;
}
return false;
}
public void add(int index, Object obj) {
try{
if (size >= capacity) this.expand();
for (int j = size; j > index; j--) items[j] = items[j - 1];
items[index] = obj;
size++;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}
public int indexOf(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return j;
}
return -1;
}
public boolean remove(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) {
for (int k = j; k < size-1; k++) items[k] = items[k + 1];
size--;
items[size] = null;
return true;
}
}
return false;
}
public Object remove(int index) {
try{
Object result = this.get(index);
for (int k = index; k < size-1; k++) items[k] = items[k + 1];
items[size] = null;
size--;
return result;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}
public void set(int index, Object obj) {
try{
items[index] = obj;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}
public Iterator<E> iterator() {
return new MyIterator<E>();
}
public class MyIterator <T> implements Iterator<T>{
public boolean hasNext(){
}
public T next(){
}
public void remove(){
}
}
}
Basically I'm trying to improve the functionality of my arraylist, as it uses for loops for methods such as add and remove, however I am trying to use an iterator instead and I searched it up and I found out you cannot just simply add implements iterable to the main class, it has to be implemented by using three methods next(), hasNext() and remove(). I added the three methods at the bottom of the code but i'm really not sure how I implement it in order for it to begin to work.
You'll need to keep track of the index in the items array that the Iterator is on. Let's call it int currentIndex. hasNext() will return true if currentIndex < size. next() will increment currentIndex if hasNext() is true and return items[currentIndex], otherwise it should throw an Exception, say NoSuchElementException. Remove will call remove(currentIndex).
Here is an example (NOTE: I have not tried to compile this or anything so please update this post if you find any errors!)
public class MyArrayList<E> implements Iterable<E> {
...
#Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private Object[] currentData = items;
private int pos = 0;
#Override
public boolean hasNext() {
return pos < currentData.length;
}
#Override
public E next() {
return (E) currentData[pos++];
}
#Override
public void remove() {
MyArrayList.this.remove(pos++);
}
};
}
}
You need to pass the items array to your MyIterator class so that you can keep track of the current position of the cursor in the array. Now based on the current position of the cursor you could implement all the abstract methods.
In the constructor of the MyIterator class pass the array as a parameter as public MyIterator(E[] array) and store the array as a local variable. also create a local variable cursor and set its value to 0.

Removing from a MultiSet

So I've been tasked to create a method to remove an element from a MultiSet. I've been trying for a while, but sadly in vain. My code is as follows:
import java.util.*;
public class MultiSet<E> extends AbstractCollection<E> {
private HashMap<E, Integer> elements;
private int noOfElems;
public MultiSet() {
elements = new HashMap<E, Integer>();
noOfElems= 0;
}
public MultiSet(Collection<E> c) {
this();
addAll(c);
}
public int size() {
return noOfElems;
}
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<E> iterator = elements.keySet().iterator();
int elemsLeft = 0;
E thisElem = null;
public boolean hasNext() {
return iterator.hasNext();
}
public E next() {
if (elemsLeft == 0) {
thisElem = iterator.next();
elemsLeft = elements.get(thisElem);
}
elemsLeft -= elemsLeft;
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public boolean add(E e) {
Integer i = elements.get(e);
if(i == null) {
i = 1;
} else {
i += 1;
}
elements.put(e, i);
noOfElems++;
return true;
}
public String toString() {
return elements.toString();
}
public int hashCode() {
return elements.hashCode();
}
public boolean equals(MultiSet<E> other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (this.getClass() != other.getClass()) {
return false;
}
MultiSet<?> obj = (MultiSet<?>) other;
return obj.elements.equals(elements);
}
public boolean remove(Object o) {
}
}
And I want to implement the remove method. Anything that will help me, even a few pointers on where to start, will be greatly appreciated. Thanks! (also, comments on the rest of my code will also be appreciated)
This multiset just stores the elements as hash keys mapped to a count of the number of occurrences. To remove all instances of an element, just delete the key:
public void remove_all(E e) {
elements.remove(e);
}
If you need to remove only one instance, then decrement the count unless it's already a 1. In that case, remove the key.
public void remove(E e) {
Integer i = elements.get(e);
if (i != null) {
if (i == 1) {
elements.remove(e);
} else {
elements.put(e, i - 1);
}
}
}
BTW it's a bit hard to believe this is your code. If you understand enough to write the methods you've already written, how could you not know even where to start on remove?

Categories

Resources