Generate SHA or MD5 file checksum hash in java. A checksum hash is an encrypted sequence of characters obtained after applying certain algorithms and manipulations on user provided content. In this post, we will learn to generate the checksum hash for files.
The java.util.HashMap.keySet method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them. Hash and unique key are two different things, but to answer your question. If you want to generate a key for a single application, then the UUID class should be fine. If it is a group of applications, meaning that you can be generating it from many applications and on many machines - then you probably need to create your own class that uses the host, pid, and probably system time. The following program shows how to generate SHA256 hash in Java. This program uses the built-in class java.security.MessageDigest for creating the SHA256 hash. Note that the hash output generated is binary data and hence if you try to convert it directly to String, you will get unprintable weird looking characters. Just to throw this out, there is a (much maligned) class named java.util.Properties that is an extension of Hashtable. It expects only String keys and values and lets you load and store the data using files or streams.
HowToDoInJavaBy Lokesh Gupta | Filed Under: Java CollectionsJava Hashtable class is an implementation of hash table data structure. It is very much similar to HashMap in Java, with most significant difference that Hashtable is synchronized while HashMap is not.
In this Hashtable tutorial, we will learn it’s internals, constructors, methods, use-cases and other important points.
1. How Hashtable Works?
Hashtable internally contains buckets in which it stores the key/value pairs. The Hashtable uses the key’s hashcode to determine to which bucket the key/value pair should map.
The function to get bucket location from Key’s hashcode is called hash function. In theory, a hash function is a function which when given a key, generates an address in the table. A hash function always returns a number for an object. Two equal objects will always have the same number while two unequal objects might not always have different numbers.
When we put objects into a hashtable, it is possible that different objects (by the equals() method) might have the same hashcode. This is called a collision. To resolve collisions, hashtable uses an array of lists. The pairs mapped to a single bucket (array index) are stored in a list and list reference is stored in array index.
1.1. Hashtable Declaration
The Hashtable class is declared as following in Java. It extends Dictionary class and implements Map,
Cloneable
and Serializable
interfaces. Here 'K'
is the type of keys and 'V'
is the type of mapped values to keys.2. Hashtable Features
The important things to learn about Java Hashtable class are:
- It is similar to HashMap, but it is synchronized while HashMap is not synchronized.
- It does not accept
null
key or value. - It does not accept duplicate keys.
- It stores key-value pairs in hash table data structure which internally maintains an array of list. Each list may be referred as a bucket. In case of collisions, pairs are stored in this list.
- Enumerator in Hashtable is not fail-fast.
3. Hashtable Constructors
Hashtable class has four constructors.
- Hashtable(): It is the default constructor. It constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75).
- Hashtable(int size): It constructs a new, empty hashtable of specified initial size.
- Hashtable(int size, float fillRatio): It constructs a new, empty hashtable of specified initial size and fill ratio.
- Hashtable(Map m): It constructs a hashtable that is initialized with the key-value pairs in specified map.
Please note that initial capacity refers to number of buckets in hashtable. An optimal number of buckets is required to store key-value pairs with minimum collisions (to improve performance) and efficient memory utilization.
The fill ratio determines how full hashtable can be before it’s capacity is increased. It’s Value lie between 0.0 to 1.0.
4. Hashtable Methods
The methods in Hashtable class are very similar to HashMap. Take a look.
- void clear() : It is used to remove all pairs in the hashtable.
- boolean contains(Object value) : It returns
true
if specified value exist within the hash table for any pair, else returnfalse
. Note that this method is identical in functionality tocontainsValue()
function. - boolean containsValue(Object value) : It returns
true
if specified value exist within the hash table for any pair, else returnfalse
. - boolean containsKey(Object key) : It returns
true
if specified key exist within the hash table for any pair, else returnfalse
. - boolean isEmpty() : It returns
true
if the hashtable is empty; returnsfalse
if it contains at least one key. - void rehash() : It is used to increase the size of the hash table and rehashes all of its keys.
- Object get(Object key) : It returns the value to which the specified key is mapped. Returns null if no such key is found.
- Object put(Object key, Object value) : It maps the specified
key
to the specifiedvalue
in this hashtable. Neither the key nor the value can benull
. - Object remove(Object key) : It removes the key (and its corresponding value) from hashtable.
- int size() : It returns the number of entries in the hash table.
5. Hashtable Example
Let’s see a example for how to use Hashtable in java programs.
Program Output.
6. Hashtable Performance
Performance wise HashMap performs in O(log(n)) in comparion to O(n) in Hashtable for most common operations such as get(), put(), contains() etc.
The naive approach to thread-safety in Hashtable (“synchronizing every method”) makes it very much worse for threaded applications. We are better off externally synchronizing a HashMap. A well thought design will perform much better than Hashtable.
Hashtable is obsolete. Best is to use ConcurrentHashMap class which provide much higher degree of concurrency.
7. Hashtable vs HashMap
Let’s quickly list down the differences between a hashmap and hashtable in Java.
- HashMap is non synchronized. Hashtable is synchronized.
- HashMap allows one null key and multiple null values. Hashtable doesn’t allow any null key or value.
- HashMap is fast. Hashtable is slow due to added synchronization.
- HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and Iterator.
- Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.
- HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
8. Conclusion
In this tutorial, we learned about Java Hashtable class, it’s constructors, methods, real life usecases and compared their performances. We also learned how a hastable is different from hashmap in Java.
Do not use Hashtable in your new applications. Use HashMap if you do not need councurrency. In concurrent environment, prefer to use ConcurrentHashMap.
Drop me your questions in comments.
Happy Learning !!
Reference:
Hashtable Java Docs
- Details
- Written by Nam Ha Minh
- Last Updated on 02 July 2019 | Print Email
![Hash list in java Hash list in java](/uploads/1/2/6/0/126072111/966573776.png)
- First approach (suitable for small-sized message):
- Second approach (suitable for large-size message, i.e. large file):
![Generate Generate](/uploads/1/2/6/0/126072111/831920870.jpg)
Generate Sha256 Hash
Now, let’s see some examples in details.1. Generating Hash from String
The following method takes a message and algorithm name as inputs and returns hexadecimal form of the calculated hash value:The HashGenerationException is a custom exception (you can find this class in the attachment). The convertByteArrayToHexString() method is implemented as follows:TheGenerate Hash Key In Java Free
hashString() is a general method. Here are four public utility methods that are specific to each algorithm (MD5, SHA-1 and SHA-256):Hence we have the following utility class:Here’s a test program:If the input message is “admin” the test program produces the following output:2. Generating Hash from File
To calculate hash value of a large file effectively, it’s recommended to repeatedly put a chunk of bytes to the message digest, until reaching end of file. Here’s such method:Here are four public methods that are specific to each algorithm:And here’s a test program:Example output:NOTES:MD5 was found insecure, so it’s recommended to use SHA-256 instead for better security.References:
Other Java Coding Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook.Create Hash Key
[Java source code] | 3 kB |