Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How can I do this problem without using the built in HashSet class? Given a inte

ID: 3679920 • Letter: H

Question

How can I do this problem without using the built in HashSet class?

Given a integer k and an IntegerSet S, the following operations should be defined: S.contains(k) returns true iff k is one of the integer values contained in S S.insert(k) adds k to the set of integer values contained in S S.remove(k) removes k from the set of integers contained in S S.empty() returns true iff S is the empty set S.size() returns the cardinality of the set S (or |S|) The following program is a trivial example of how your class will be tested.

Given two IntegerSet object A and B, the following operations should be defined:

A.union(B) returns an IntegerSet object that contains elements in A and B A.intersection(B) returns an IntegerSet object that contains elements that are both in A and B

Explanation / Answer

import java.util.HashMap;
import java.util.Map;

public class IntegerSet {

   private Map<Integer, Object> set;
   private static final Object PRESENT = new Object();

   public IntegerSet() {
       set = new HashMap<>();
   }

   private IntegerSet(Map<Integer, Object> setTmp) {
       this.set = setTmp;
   }

   public void Insert(int number) {
       set.put(number, PRESENT);
   }

   public boolean contains(int number) {
       return set.containsKey(number);
   }

   public void remove(int number) {
       set.remove(number);
   }

   public boolean isEmpty() {
       return set.isEmpty();
   }

   public int size() {
       return set.size();
   }

   private Map<Integer, Object> getMap() {
       return set;
   }

   public IntegerSet union(IntegerSet B) {
       Map<Integer, Object> setTmp = new HashMap<>();
       setTmp.putAll(this.getMap());
       setTmp.putAll(B.getMap());
       IntegerSet tmp = new IntegerSet(setTmp);

       return tmp;
   }

   public IntegerSet interSection(IntegerSet B) {
       Map<Integer, Object> tmp = new HashMap<>(this.getMap());
       tmp.keySet().retainAll(B.getMap().keySet());

       return new IntegerSet(tmp);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote