Question

This laboratory assignment involves implementing a data structure called a map. A map associates objects called...

This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally.

1. Theory.

A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps.

  • You can test if a key has a value in the map.

  • You can add a new key-value pair to the map.

  • You can get the value that is associated with a given key.

  • You can change the value that is associated with a given key.

For example, the keys might be String’s that are the English words for numbers. The values might be Integer’s that are the numbers corresponding to those words. If you give the map an English word (like "ten") then you can get back its corresponding number (like 10).
      The maps for this assignment use arrays, and they work by doing linear search on those arrays. As a result, if a map has n pairs, then its operations may need at most O(n) key comparisons. However, there are better ways to implement maps, using data structures that we have not yet discussed in this course. These require only O(log n) or even O(1) key comparisons.

2. Implementation.

You must write a Java class called Map that implements a map. To simplify grading, your class must use the same names for things that are given here. Your class Map must have two generic class parameters, Key and Value, so it looks like this. Here Key is the type of the map’s keys, and Value is the type of the map’s values.

class Map
{
  ⋮
}

Within the class Map, you must have two private arrays called keys and values. The array keys must be an array whose base type is the class parameter Key. The array values must be an array whose base type is the class parameter Value. Suppose that a key k is found at the index i in the array keys. Then the value associated with k is found at the same index i in the array values. Do not try to use only one array, because that will not work.
      You must also have a private integer variable called count that records how many elements of the arrays are being used. You may also need other private variables that are not mentioned here.
      Your class must have the following methods. Most of them use count, keys, and values somehow. Some methods are public and others are private. The private methods are helpers for the public methods; they may make your code easier to write. Also, any key may be null, and any value may be null. This will affect how you test if keys are equal.

public Map(int length)

Constructor. If length is less than 0 then you must throw an IllegalArgumentException. Otherwise, initialize an empty Map whose keys and values arrays have length elements. (Recall that you must make arrays of Object’s, then cast them to the appropriate types.)

public Value get(Key key)

Search the array keys for an element that is equal to key. If that element is at some index in keys, then return the element at the same index in the array values. If there is no element equal to key in keys, then throw an IllegalArgumentException.

private boolean isEqual(Key leftKey, Key rightKey)

Test if leftKey is equal to rightKey. Either or both may be null. This method is necessary because you must use == when leftKey or rightKey are null, but you must use the equals method when both are not null. (Recall that null has no methods.)

public boolean isIn(Key key)

Test if there is an element in keys that is equal to key.

public void put(Key key, Value value)

Search the array keys for an element that is equal to key. If that element is at some index in keys, then change the element at the same index in values to value. If there is no element in keys that is equal to key, then add key to keys, and add value at the same index in values. If keys and values are full, so you cannot add key and value, then throw an IllegalStateException.

private int where(Key key)

Search the array keys for an element that is equal to key. Return the index of that element. If there is no element equal to key in keys, then return −1.

When you compile your program, you may see the following ‘‘warning’’ messages from javac. Ignore them. As discussed in the lectures, these messages appear because Java does not implement class parameters (the names between < and >) correctly.

Note: your file name.java uses unchecked or unsafe operations.
Note: recompile with -Xlint:unchecked for details.

The file tests5.java on Canvas contains Java code that performs a series of tests, worth 40 points. Each test calls a public method from your class Map, and prints what the method returns. Each test is also followed by a comment that tells how many points it is worth, and what it must print if it works correctly. You may want to run additional tests, but you don’t get points for those.

below is the test.java

// Each test has a comment that shows what it should print and how many points
// it is worth, for a total of 40 points.
//

// HOGWARTS. The Hogwarts dating service.

class Hogwarts
{

// MAIN. Make an instance of MAP and test it.

public static void main(String [] args)
{
Map map;

try
{
map = new Map(-5);
}
catch (IllegalArgumentException ignore)
{
System.out.println("No negatives"); // No negatives 2 points.
}

map = new Map(5);

map.put("Harry", "Ginny");
map.put("Ron", "Lavender");
map.put("Voldemort", null);
map.put(null, "Wormtail");

System.out.println(map.isIn("Harry")); // true 2 points.
System.out.println(map.isIn("Ginny")); // false 2 points.
System.out.println(map.isIn("Ron")); // true 2 points.
System.out.println(map.isIn("Voldemort")); // true 2 points.
System.out.println(map.isIn(null)); // true 2 points.
System.out.println(map.isIn("Joanne")); // false 2 points.

System.out.println(map.get("Harry")); // Ginny 2 points.
System.out.println(map.get("Ron")); // Lavender 2 points.
System.out.println(map.get("Voldemort")); // null 2 points.
System.out.println(map.get(null)); // Wormtail 2 points.

try
{
System.out.println(map.get("Joanne"));
}
catch (IllegalArgumentException ignore)
{
System.out.println("No Joanne"); // No Joanne 2 points.
}

map.put("Ron", "Hermione");
map.put("Albus", "Gellert");
map.put(null, null);

System.out.println(map.isIn(null)); // true 2 points.
System.out.println(map.isIn("Albus")); // true 2 points.

System.out.println(map.get("Albus")); // Gellert 2 points.
System.out.println(map.get("Harry")); // Ginny 2 points.
System.out.println(map.get("Ron")); // Hermione 2 points.
System.out.println(map.get("Voldemort")); // null 2 points.
System.out.println(map.get(null)); // null 2 points.

try
{
map.put("Draco", "Pansy");
}
catch (IllegalStateException minnesota)
{
System.out.println("No Draco"); // No Draco 2 points.
}
}
}

Homework Answers

Answer #1

Hi,

below is the java code for the above implementation of map of key and value pair .

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
   }
}

Note:- I have changed the names while implementing the code, you can use the original one.

Thank you!

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
JAVA please Arrays are a very powerful data structure with which you must become very familiar....
JAVA please Arrays are a very powerful data structure with which you must become very familiar. Arrays hold more than one object. The objects must be of the same type. If the array is an integer array then all the objects in the array must be integers. The object in the array is associated with an integer index which can be used to locate the object. The first object of the array has index 0. There are many problems where...
Write code in java Implement a method to build an AVL tree out of a sorted...
Write code in java Implement a method to build an AVL tree out of a sorted (ascending order) array of unique integers, with the fastest possible big O running time. You may implement private helper methods as necessary. If your code builds a tree that is other than an AVL tree, you will not get any credit. If your code builds an AVL tree, but is not the fastest big O implementation, you will get at most 12 points. You...
In java create a dice game called sequences also known as straight shooter. Each player in...
In java create a dice game called sequences also known as straight shooter. Each player in turn rolls SIX dice and scores points for any sequence of CONSECUTIVE numbers thrown beginning with 1. In the event of two or more of the same number being rolled only one counts. However, a throw that contains three 1's cancels out player's score and they mst start from 0. A total of scores is kept and the first player to reach 100 points,...
Java Program: You will be inserting values into a generic tree, then printing the values inorder,...
Java Program: You will be inserting values into a generic tree, then printing the values inorder, as well as printing the minimum and maximum values in the tree. Given main(), write the methods in the 'BSTree' class specified by the // TODO: sections. There are 5 TODOs in all to complete. Ex: If the input is like ferment bought tasty can making apples super improving juice wine -1 the output should be: Enter the words on separate lines to insert...
Finish the code wherever it says TODO /**    * Node type for this list. Each...
Finish the code wherever it says TODO /**    * Node type for this list. Each node holds a maximum of nodeSize elements in an    * array. Empty slots are null.    */    private class Node {        /**        * Array of actual data elements.        */        // Unchecked warning unavoidable.        public E[] data = (E[]) new Comparable[nodeSize];        /**        * Link to next node.       ...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as possible: What is a checked exception, and what is an unchecked exception? What is NullPointerException? Which of the following statements (if any) will throw an exception? If no exception is thrown, what is the output? 1: System.out.println( 1 / 0 ); 2: System.out.println( 1.0 / 0 ); Point out the problem in the following code. Does the code throw any exceptions? 1: long value...
The following program creates a linked list which contains 5 links. Add a method called doubleValue()...
The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list. public class Link { private int number; private Link next;      public Link(int x) { number = x; }    public void displayLink() { System.out.println("The number is:...
The following program creates a linked list which contains 5 links. Add a method called doubleValue()...
The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list. public class Link { private int number; private Link next;      public Link(int x) { number = x; }    public void displayLink() { System.out.println("The number is:...
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
Write a program that sorts the content of a map by Values. Before we start, we...
Write a program that sorts the content of a map by Values. Before we start, we need to check the explanation of Java Map Interface and Java LinkedHashMap. This program can be implemented as follows: 1. Create a LinkedHashMap class <String (Country), String(Capital)> that stores Capitals of FIVE countries. 2. Use sortMap() for receiving content of the created class of LinkedHashMap and reorder it in a sorted Map. (sort in natural order). 3. You need to transfer the map into...