A small coding test that I encountered today.

Question

Using only primitive types, implement a fixed-size hash map that associates string keys with arbitrary data object references (you don't need to copy the object). Your data structure should be optimized for algorithmic runtime and memory usage. You should not import any external libraries, and may not use primitive hash map or dictionary types in languages like Python or Ruby.

The solution should be delivered in one class (or your language's equivalent) that provides the following functions:

  • constructor(size): return an instance of the class with pre-allocated space for the given number of objects.
  • boolean set(key, value): stores the given key/value pair in the hash map. Returns a boolean value indicating success / failure of the operation.
  • get(key): return the value associated with the given key, or null if no value is set.
  • delete(key): delete the value associated with the given key, returning the value on success or null if the key has no value.
  • float load(): return a float value representing the load factor (`(items in hash map)/(size of hash map)`) of the data structure. Since the size of the dat structure is fixed, this should never be greater than 1.

If your language provides a built-in hashing function for strings (ex. `hashCode` in Java or `__hash__` in Python) you are welcome to use that. If not, you are welcome to do something naive, or use something you find online with proper attribution.

Solution

Key to construct a hash map is to construct several key-value entries.

 package datastructures.map;

 public class MyEntry<K, V> {
private final K key;
private V value; public MyEntry(K key, V value) {
this.key = key;
this.value = value;
} public K getKey() {
return key;
} public V getValue() {
return value;
} public void setValue(V value) {
this.value = value;
}
}
 package datastructures.map;

 // import datastructures.map.MyEntry;

 public class MyMap<K, V> {
private int fullSize;
private int size;
private int DEFAULT_CAPACITY = 16; private MyEntry<K, V>[] map = new MyEntry[DEFAULT_CAPACITY]; public MyMap(int size) {
this.size = 0;
this.map = new MyEntry[size];
this.fullSize = size;
} public V get(K key) {
for (int i = 0; i < size; i++) {
if (map[i].getKey().equals(key)) {
return map[i].getValue();
}
}
return null;
} public boolean set(K key, V value) {
boolean insert = true;
for (int i = 0; i < size; i++) {
if (map[i].getKey().equals(key)) {
map[i].setValue(value);
insert = false;
}
}
if (insert) {
if (size >= fullSize) {
return false;
}
else {
map[size] = new MyEntry(key, value);
size++;
}
}
return true;
} public V delete(K key) {
for (int i = 0; i < size; i++) {
if (map[i].getKey().equals(key)) {
V value = map[i].getValue();
map[i] = null;
condenseArray(i);
return value;
}
}
return null;
} public float load() {
return (float)size / (float)fullSize;
} private void condenseArray(int start) {
size--;
for (int i = start; i < size; i++) {
map[i] = map[i + 1];
}
} }
 package datastructures.map;

 public class Test {
public static void main(String[] args) {
int size = 8;
MyMap<Character, Integer> test = new MyMap<Character, Integer>(size);
test.set('a', 1);
test.set('b', 2);
test.set('c', 3);
test.set('d', 4);
System.out.println(test.get('a'));
System.out.println(test.set('a', 2));
System.out.println(test.get('a'));
System.out.println(test.load());
test.delete('b');
System.out.println(test.load());
}
}

More basic knowledge about Java

Package and Import

Classes under same package need not import each other.

Here, we set three classes in package datastructures.map, and my current path is /home/Desktop

Then, I need to make a directory of datastructures/map under Desktop and put three source codes in that directory.

Meanwhile, I need to compile under Desktop directory.

Tutorialspoint

To compile the Java programs with package statements you have to do use -d option as shown below.

javac -d Destination_folder file_name.java

There can be only one package statement in each source file, and it applies to all types in the file.

Two major results occur when a class is placed in a package:

1. The name of the package becomes a part of the name of the class, as we just discussed in the previous section.

2. The name of the package must match the directory structure where the corresponding bytecode resides.

Constructor

Constructor for object should not include inner types.

For example

public MyMap<K, V>() {}           is wrong!

public MyMap() {}         is right!

Public Class

(referrence: Tutorialspoint)

Four access level for classes:

1. Visible to the package. the default. No modifiers are needed.

2. Visible to the class only (private).

3. Visible to the world (public).

4. Visible to the package and all subclasses (protected).

Access Control and Inheritance:

1. Methods declared public in a superclass also must be public in all subclasses.

2. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.

3. Methods declared without access control (no modifier was used) can be declared more private in subclasses.

4. Methods declared private are not inherited at all, so there is no rule for them.

Implement Hash Map Using Primitive Types的更多相关文章

  1. Hash Map (Hash Table)

    Reference: Wiki  PrincetonAlgorithm What is Hash Table Hash table (hash map) is a data structure use ...

  2. Java中的原始类型(Primitive Types)与引用类型(Reference Values)

    Java虚拟机可以处理的类型有两种,一种是原始类型(Primitive Types),一种是引用类型(Reference Types). 与之对应,也存在有原始值(Primitive Values)和 ...

  3. Effective Java 49 Prefer primitive types to boxed primitives

    No. Primitives Boxed Primitives 1 Have their own values Have identities distinct from their values 2 ...

  4. How to Map Distinct Value Types Using Java Generics--reference

    原文:http://www.codeaffine.com/2015/03/04/map-distinct-value-types-using-java-generics/ Occasionally t ...

  5. hdu1381 Crazy Search(hash map)

    题目意思: 给出一个字符串和字串的长度,求出该字符串的全部给定长度的字串的个数(不同样). 题目分析: 此题为简单的字符串哈hash map问题,能够直接调用STL里的map类. map<str ...

  6. C# 01 Primitive Types and Expressions

    Class Data or Attributes state of the application Methods or Functions have behavior Namespace is a ...

  7. [LeetCode] Repeated DNA Sequences hash map

    All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACG ...

  8. Hash Map 在java中的解释及示例

    目录 HashMap在java中的应用及示例 HashMap的内部结构 HashMap的性能 同步HashMap HashMap的构造函数 HashMap的时间复杂度 HashMap的方法 1. vo ...

  9. Redis的增删改查 c# key value类型和hash map 类型

    using Newtonsoft.Json; using StackExchange.Redis; using System; using System.Collections.Generic; us ...

随机推荐

  1. unix c 10

    网络常识:    OSI 7层模型  TCP模型    IP和端口    IP是用来定位网络中的计算机,端口用来代表 计算机中的某个进程.    IP 有点分十进制 和 十六进制的两种表示方式,底层 ...

  2. vi命令笔记

    vim编辑器 文本编辑器,字处理器ASCII nano, sed vi: Visual Interfacevim: VI iMproved 全屏编辑器,模式化编辑器 vim模式:编辑模式(命令模式)输 ...

  3. handsontable的单元格操作方法

    1.为handsontable添加钩子方法 addHook(key,callback):key为钩子方法名 <span style="font-size:18px;"> ...

  4. InnoDB和MyISAM存储引擎的区别

    在MySQL数据库的使用过程中我们经常会听到存储引擎这个名词.MySQL的存储引擎有好多种如InnoDB.MyISAM.Memory.NDB等等,多存储引擎也是MySQL数据库的特色. InnoDB和 ...

  5. JConsole 连接配置

    远程监控配置 JDK配置 在%JAVA_HOME%/jre/lib/management目录下,jmxremote.password.template.jmxremote.password需要修改配置 ...

  6. 用CSS3实现对图片的放大效果

    用CSS3对图片放大效果 .right_div .topicons li a:hover img{     -webkit-transform:scale(1.5,1.5);     -moz-tra ...

  7. NSSCanner 提取 指定 字符串

    /** *  从msg中提取指定的内容 * *  @param msg 字符串集合 * *  @return 从msg中提取指定的内容 */ -(NSString*)extractBodyFromMe ...

  8. Android应用程序安装过程源代码分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6766010 Android系统在启动的过程中, ...

  9. Java中String直接赋字符串和new String的区别

    解析Java中的String对象的数据类型 1. String是一个对象.  因为对象的默认值是null,所以String的默认值也是null:但它又是一种特殊的对象,有其它对象没有的一些特性. 2. ...

  10. SQLLoader4(数据文件中的列与表中列不一致情况-filler)

    A.数据文件中字段个数少于表中列字段个数,但数据文件中缺少的列,在表定义中可以为空.----- 这种情况是比较简单的,只需要将数据文件中数据对应的列的名字写到控制文件中即可.因为SQL*Loader是 ...