Question

In: Computer Science

package SOLUTION; import java.util.Collection; import java.util.Set; public interface MapInterface<K, V> {       /**    *...

package SOLUTION;

import java.util.Collection;
import java.util.Set;

public interface MapInterface<K, V> {
  
   /**
   * If the given key is not already in the map, adds the
   * key-value pair to the map. Otherwise, updates the old
   * value of the existing key to the specified value.
   * @param key the key
   * @param value the value to be stored in the map with the key
   * @return null if the key was not already in the map, or
   * the old value associated with the key if the key was already in the map
   */
   public V put(K key, V value);
  
   /**
   * Gets the value from the map that is associated with the given key
   * @param key the key
   * @return the value associated with the key, or null if the key is
   * not in the map
   */
   public V get(K key);
  
   /**
   * Removes from the key-value pair associated with the specified key
   * @param key the key
   * @return the value associated with the key, or null if the key is
   * not in the map
   */
   public V remove(K key);
  
   /**
   * Returns whether the map contains the key-value pair associated with
   * the specified key
   * @param key the key
   * @return true if the map contains a key-value pair with the specified
   * key, and false otherwise
   */
   public boolean containsKey(K key);
  
   /**
   * Returns whether the map contains no elements
   * @return true if the map contains no key-value pairs, and false otherwise
   */
   public boolean isEmpty();
  
   /**
   * Removes all elements from the map
   */
   public void clear();
  
   /**
   * Gets the number of key-value pairs in the map
   * @return the number of key-value pairs in the map
   */
   public int size();
  
   /**
   * Gets a set of all keys in the map
   * @return
   */
   public Set<K> keySet();

   /**
   * Gets a set of all values in the map
   * @return
   */
   public Collection<V> values();

}

package SOLUTION;
public class Tester {

   public static void main(String[] args) {
       ArrayListMap<String, Integer> alm = new ArrayListMap<String, Integer>();
      
       System.out.println(alm.put("Cindy", 1));
       System.out.println(alm.put("Nina", 2));
       System.out.println(alm.put("Morgan", 3));
       System.out.println(alm.put("Michael", 4));
      
       System.out.println(alm.size());
       System.out.println(alm.containsKey("Morgan"));
       System.out.println(alm.containsKey("Jack"));
       System.out.println(alm.get("Michael"));
       System.out.println(alm.values());
       System.out.println(alm.keySet());
       System.out.println(alm.put("Michael", 6));
       System.out.println(alm.get("Michael"));
       System.out.println(alm.remove("Michael"));
       System.out.println(alm.remove("Morgan"));
       System.out.println(alm.remove("Nina"));
       System.out.println(alm.remove("Cindy"));
       System.out.println(alm.size());
   }
  
}

Solutions

Expert Solution

Summary:

Below ArrayListMap class is the implementation of the map interface. In this class we are implementing methods like put, get, remove, containKey and some other map related functions.

Its very program and I have added comments wherever required so that you can understand the logic.

-----------------------------------------------MapInterface.java-------------------------------------

import java.util.Collection;
import java.util.Set;

public interface MapInterface<K, V> {

    /**
     * If the given key is not already in the map, adds the
     * key-value pair to the map. Otherwise, updates the old
     * value of the existing key to the specified value.
     * @param key the key
     * @param value the value to be stored in the map with the key
     * @return null if the key was not already in the map, or
     * the old value associated with the key if the key was already in the map
     */
    public V put(K key, V value);

    /**
     * Gets the value from the map that is associated with the given key
     * @param key the key
     * @return the value associated with the key, or null if the key is
     * not in the map
     */
    public V get(K key);

    /**
     * Removes from the key-value pair associated with the specified key
     * @param key the key
     * @return the value associated with the key, or null if the key is
     * not in the map
     */
    public V remove(K key);

    /**
     * Returns whether the map contains the key-value pair associated with
     * the specified key
     * @param key the key
     * @return true if the map contains a key-value pair with the specified
     * key, and false otherwise
     */
    public boolean containsKey(K key);

    /**
     * Returns whether the map contains no elements
     * @return true if the map contains no key-value pairs, and false otherwise
     */
    public boolean isEmpty();

    /**
     * Removes all elements from the map
     */
    public void clear();

    /**
     * Gets the number of key-value pairs in the map
     * @return the number of key-value pairs in the map
     */
    public int size();

    /**
     * Gets a set of all keys in the map
     * @return
     */
    public Set<K> keySet();

    /**
     * Gets a set of all values in the map
     * @return
     */
    public Collection<V> values();

}

--------------------------------------------------ArrayListMap.java-----------------------------

import java.util.*;

/**
 * This class is the implementation of Map Interface.
 * @param <String>
 * @param <Integer>
 */
public class ArrayListMap<String,Integer> implements MapInterface<String,Integer>{
    private List<ArrayListMap<String,Integer>> arrayListMaps = new ArrayList<>();

    String key;
    Integer value;
    private static int size =0;


    ArrayListMap(){

    }

    ArrayListMap(String key, Integer value){
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Integer getValue() {
        return value;
    }

    public void setValue(Integer value) {
        this.value = value;
    }

    @Override
    public Integer put(String key, Integer value) {

        // Loop through all the key value pair to check if key already exist
        for (int k = 0; k<size ; k++) {
            if (arrayListMaps.get(k).getKey().equals(key)) {
                // if key exist update the value
                Integer temp = (Integer) arrayListMaps.get(k).getValue();
                arrayListMaps.get(k).setValue(value);
                return temp;
            }
        }
        // if new key then add the new key, value pair
        arrayListMaps.add(new ArrayListMap(key, value));
        size++;
        return null;
    }


    @Override
    public Integer get(String key) {
        // Loop through all the key value pair to check if key already exist
        for (int i = 0; i<size ; i++) {
            if (arrayListMaps.get(i).getKey().equals(key)) {
                // if key exist return the value
                return  (Integer) arrayListMaps.get(i).getValue();
            }
        }
        return null;
    }

    @Override
    public Integer remove(String key) {
        // Loop through all the key value pair to check if key already exist
        for (int i = 0; i<size ; i++) {
            if (arrayListMaps.get(i).getKey().equals(key)) {
                // if key exist remove the key,value pair from arrayListMaps list.
                Integer temp = (Integer) arrayListMaps.get(i).getValue();
                arrayListMaps.remove(arrayListMaps.get(i));
                size--;
                return temp;
            }

        }
        return null;
    }

    @Override
    public boolean containsKey(String key) {
        for (int i = 0; i<size ; i++) {
            if (arrayListMaps.get(i).getKey().equals(key)) {
                return true;
            }

        }
        return false;
    }

    @Override
    public boolean isEmpty() {
        return size==0 ? true : false;
    }

    @Override
    public void clear() {

    }

    @Override
    public int size() {
        return this.size;
    }

    @Override
    public Set<String> keySet() {
        Set<String> stringSet = new LinkedHashSet<>();
        for (int i = 0; i<size ; i++) {
            stringSet.add(arrayListMaps.get(i).getKey());
        }
        return stringSet;
    }

    @Override
    public Collection<Integer> values() {
        Set<Integer> valueSet = new LinkedHashSet<>();
        for (int i = 0; i<size ; i++) {
            valueSet.add(arrayListMaps.get(i).getValue());
        }
        return valueSet;
    }

}

------------------------------------------------------Tester.java--------------------------------------------------


public class Tester {

    public static void main(String[] args) {
        ArrayListMap alm = new ArrayListMap();

        System.out.println(alm.put("Cindy", 1));
        System.out.println(alm.put("Nina", 2));
        System.out.println(alm.put("Morgan", 3));
        System.out.println(alm.put("Michael", 4));

        System.out.println(alm.size());
        System.out.println(alm.containsKey("Morgan"));
        System.out.println(alm.containsKey("Jack"));
        System.out.println(alm.get("Michael"));
        System.out.println(alm.values());
        System.out.println(alm.keySet());
        System.out.println(alm.put("Michael", 6));
        System.out.println(alm.get("Michael"));
        System.out.println(alm.remove("Michael"));
        System.out.println(alm.remove("Morgan"));
        System.out.println(alm.remove("Nina"));
        System.out.println(alm.remove("Cindy"));
        System.out.println(alm.size());
    }

}

Output:

Connected to the target VM, address: '127.0.0.1:51272', transport: 'socket'
null
null
null
null
4
true
false
4
[1, 2, 3, 4]
[Cindy, Nina, Morgan, Michael]
4
6
6
3
2
1
0
Disconnected from the target VM, address: '127.0.0.1:51272', transport: 'socket'

Process finished with exit code 0

Hope you like this answer. Enjoy!!!


Related Solutions

package design; public interface Employee { /*Employee is an Interface which contains multiple unimplemented methods.Again few...
package design; public interface Employee { /*Employee is an Interface which contains multiple unimplemented methods.Again few methods has been declared in below. you need to brainstorm to add more methods to meet the business requirements. */ //please read the following method and understand the business requirements of these following methods //and then implement these in a concrete class. //employeeId() will return employee id. public int employeeId(); //employeeName() will return employee name public String employeeName(); //assignDepartment() will assign employee to departments...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public...
create code for deletestudentbyID Number for choice == 4 package courseecom616; import java.util.Scanner; import java.util.ArrayList; public class CourseeCOM616 {        private String courseName;     private String[] studentsName = new String[1];     private String studentId;        private int numberOfStudents;        public CourseeCOM616(String courseName) {         this.courseName = courseName;     }     public String[] getStudentsName() {         return studentsName;     }     public int getNumberOfStudents() {         return numberOfStudents;     }     public String getStudentId() {         return studentId;    ...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void...
Using the following in Java- package intersectionprinter; import java.awt.Rectangle; public class IntersectionPrinter { public static void main(String[] args) { Rectangle r1 = new Rectangle(0,0,100,150); System.out.println(r1);    Rectangle r2 = new Rectangle(50,75,100,150); System.out.println(r2);    Rectangle r3 = r1.intersection(r2);    } } Write a program that takes both Rectangle objects, and uses the intersection method to determine if they overlap. If they do overlap, then print it's coordinates along with its width and height. If there is no intersection, then have the...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
import java.util.*; class A { int i, j, k; public A(int i, int j, int k)...
import java.util.*; class A { int i, j, k; public A(int i, int j, int k) { this.i=i; this.j=j; this.k=k; } public String toString() { return "A("+i+","+j+","+k+")"; } } class Main { public static void main(String[] args) { ArrayList<A> aL=new ArrayList<A>(); Random rand= new Random(1000); //1000 is a seed value for (int p=0; p<10; p++) { int i = rand.nextInt(100); int j = rand.nextInt(200); int k = rand.nextInt(300); aL.add(new A(i, j, k)); } System.out.println("----- Original arraylist------"); for (A a: aL)...
Consider the following interface: public interface Car{ public String getMake(); public void setMake(); public void honk();...
Consider the following interface: public interface Car{ public String getMake(); public void setMake(); public void honk(); public void crash(); public void drive(); } public interface Boat{ public String getMake (); public void setMake (); public void blast_horn(); public void sink(); public void move(); } 1. Create a concrete FamilyCar class from the Car interface.
I can't figure out why this won't run. //CryptographyTest.java //package cryptography; import java.util.Scanner; public class CryptographyTest...
I can't figure out why this won't run. //CryptographyTest.java //package cryptography; import java.util.Scanner; public class CryptographyTest {    public static void main(String[] args) { // create a scanner object to read from user Scanner s = new Scanner(System.in); // prompt user for input option while(true) { // loop till user say exit System.out.println("Select Option:"); System.out.println("1. Encrypt"); System.out.println("2. Decrypt"); System.out.println("3. Exit"); String input = s.nextLine(); // get user input int option = 0; try { // check for valid input option...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) {...
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Exercise { public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] WordsCharsLetters = {0,1,2}; while(input.hasNext()) { String sentence=input.nextLine(); if(sentence!=null&&sentence.length()>0){ WordsCharsLetters[0] += calculateAndPrintChars(sentence)[0]; WordsCharsLetters[1] += calculateAndPrintChars(sentence)[1]; WordsCharsLetters[2] += calculateAndPrintChars(sentence)[2]; } else break; } input.close(); System.out.println("Words: " + WordsCharsLetters[0]); System.out.println("Characters: " + WordsCharsLetters[1]); System.out.println("Letters: " + WordsCharsLetters[2]); } static int[] calculateAndPrintChars(String sentence) { int[] WCL = new int[3]; String[] sentenceArray=sentence.split(" "); WCL[0] = sentenceArray.length; int letterCount=0; for(int i=0;i<sentence.length();i++) { if(Character.isLetter(sentence.charAt(i))) letterCount++; } WCL[1]...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r =...
import java.util.Random; import java.util.Scanner; public class Compass { public Random r; public Compass(long seed){ r = new Random(seed); }    public static String numberToDirection(int a){ if(a==0) return "North";    if(a==1) return "NorthEast"; if(a==2) return "East"; if(a==3) return "Southeast"; if(a==4) return "South"; if(a==5) return "Southwest"; if(a==6) return "West";    if(a==7) return "Northwest";    return "Invalid Direction" ; } public String randomDirection(){ return numberToDirection(r.nextInt()% 4 + 1); } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter seed: ");...
import java.util.LinkedList; import java.util.Queue; import java.time.*; public class CheckOutLine { /** This is the main function...
import java.util.LinkedList; import java.util.Queue; import java.time.*; public class CheckOutLine { /** This is the main function for the program */ public static void main() { System.out.println("\n\tBegin CheckOutLine Demo\n"); System.out.println("\nCreating a Queue called \"register\" based on a LinkedList"); Queue<Customer> register = new LinkedList<Customer>();    System.out.println("\nAdding Customers to the Register queue"); // 1. TO DO: add five or more customers to the register line (5 Pts) // format: register.add(new Customer(name, checkout time));                System.out.printf("Register line has %d customers\n",...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT