Question: Implement the TODO methods in JAVA. (Task : Implement map using a sorted List) CODE: import java.util.List; import java.util.ArrayList; public class SortedListMap implements Map {

Implement the TODO methods in JAVA. (Task : Implement map using a sorted List)

CODE:

import java.util.List; import java.util.ArrayList;

public class SortedListMap, V> implements Map { /* * This nested class contains a completed implementation of Entry * which you should use within SortedListMap. * * You do not need to edit this class. */ private class Entry, V> { private K key; private V value; public Entry(K key, V value) { this.key = key; this.value = value; } public K getKey() {return key;} public V getValue() {return value;} public void setKey(K key) {this.key = key;} public void setValue(V value) {this.value = value;} } // The entry list private final List> entries = new ArrayList<>(); @Override public int size() { return entries.size(); } @Override public boolean isEmpty() { return entries.isEmpty(); } // TODO: implement the remaining methods! /** * Tests whether the map contains the given key. * * @param k * a key * @return true if the map contains the given key, false otherwise */ @Override public boolean containsKey(K key) { // TODO return false; } /** * Returns the value associated with the given key if any. * * @param k * a key * @return the value associated with the given key (or null if none present) */ @Override public V get(K key) { //TODO return null; }

/** * Inserts an entry into the map with the given key and value. * * @param k * a key * @param v * a value */

@Override public void put(K key, V value) { //TODO } /** * Removes the value associated with the given key if any, and returns it. * * @param k * a key * @return the removed value (or null if none present) */

@Override public V remove(K key) { //TODO return null; } // Returns index of entry with key, or -1 if not found private int binarySearch(K key) { int min = 0; int max = entries.size(); while (min < max) { int mid = (max + min)/2; K midKey = entries.get(mid).key; if (midKey.equals(key)) { return mid; } else if (midKey.compareTo(key) < 0) { // key after midKey min = mid + 1; } else { // key before midKey max = mid; } } // not found return -1; } public static void main(String[] args) { System.out.println("Running the main method in SortedListMap"); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!