DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • AI Agents and Frontier Models: Insights From The Neuron
  • Building a Real Pipeline With senro: Monorepos, Caching, and Triggers
  • Kill the Worker, Keep the Research: Build a Recoverable LangGraph Agent on Temporal
  • Why Your AI Agent Works in the Demo and Fails in Production

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Hashing in Java vs. C++

Hashing in Java vs. C++

Check out this post where we explore the differences — and similarities — between hashing in Java and C++.

By 
Christopher Lamb
·
Dec. 13, 19 · Analysis
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
52.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Learn more about the differences and similarities between hashing in Java and C++.

Java and C++ are somewhat syntactically similar languages that have diverged over time. Java was loosely inspired by C++, but initially didn't adopt C++'s template structures, nor did it require C++'s header/content file separation, and of course, it used the JVM and compiled to bytecode rather than machine code.

Since then, the two languages have converged somewhat — they follow similar coding guidelines, support Lamda constructs, Generics/Templates, multiple identicals for loop syntaxes, and so on. There are certainly differences in modern use, however. C++ templates support specialization, while Java generics support type restrictions. They have similar base collection types as well.

You may also like: How HashMap Works in Java

Hash tables, hash maps, and similar types of data structures that allow indexing by a unique key, but that indexing is implemented in a very specific way. Now, any associative container type can give you access to data by a particular key. You can use a linked list as your storage structure, or a doubly-linked list, or a binary tree, for example. Hash tables use, essentially, an array, but that array is indexed by a hash value. Java has, as it's base associative container type, the  java.util.HashMap class. C++ has  std::unordered_map.

Hash-based containers have significant advantages for data storage. Both containers (HashMap and  unordered_map) have O(1) lookup performance when using hash generators that have a low probability of collision. The more likely collisions, the closer the performance of the container to O(n), where n is the number of elements stored in the container. Both containers use a standard hashing function as well — Java requires keys to implement Comparable, and via Map.Entry implement the hashCode() method. For common use, they are very similar as well.

For a C++ program, you'll include something like this:

C++




x


 
1
#include <unordered_map>
2
 
          
3
std::unordered_map<std::string, unsigned int> empty_map;
4
empty_map["zero"] = 0;



Doing something similar in Java:

Java




xxxxxxxxxx
1


 
1
import java.util.HashMap;
2
 
          
3
var emptyMap = new HashMap<String, Integer>();
4
emptyMap.put("zero", 0);



Accessing variables is similar too:

C++




xxxxxxxxxx
1


 
1
auto v_0 = string_map["zero"];
2
 
          
3
std::cout << "zero value: " << v_0 << std::endl;



And in Java:

Java




xxxxxxxxxx
1


 
1
var zero = map.get("zero");
2
 
          
3
System.out.println("empty map zero: " + zero);



There are other common uses for hash structures other than putting/getting though. Another typical use involves storing string keys and specific values associated with those keys, where the key has some kind of semantic value (like a name, for example). When you do this kind of thing, you usually want to grab a collection of keys that you can then process to find a specific value. This kind of operation looks like this:

C++




xxxxxxxxxx
1


 
1
for (const auto& pair : string_map) {
2
    std::cout << "key is: " << pair.first << std::endl;
3
}



And again in Java:

Java




xxxxxxxxxx
1


 
1
for (final var k : emptyMap.keySet()) {
2
    System.out.println("key is: " + k);
3
}



We do have some C++-isms creeping in — specifically the use of a reference object in the loop. Still, things are very similar between the two languages.

The final case I'm going to take a look at is how you can apply an algorithm over all the elements of a map. First, C++:

C++




xxxxxxxxxx
1
15
9


 
1
std::for_each(
2
    string_map.begin(),
3
    string_map.end(),
4
    [&](auto& p){
5
        ++p.second;
6
        std::cout << p.second << std::endl;
7
    }
8
);



Then Java:

Java




xxxxxxxxxx
1


 
1
emptyMap.forEach((k, v) -> {
2
  ++v;
3
  System.out.println(v);
4
});



The Java version is certainly a bit terser. These two approaches also show a distinct difference in design philosophy.

The C++ version uses an external algorithm from the standard library in order to apply the lambda expression to the pairs in the map. In modern C++, classes are designed with a strict type-centric perspective. Here, the for_each(.) algorithm can be applied to any number of containers and is designed in that way. Furthermore, as it isn't intrinsic to the  unordered_map type, it is actually defined as an external function. The Java HashMap class, on the other hand, includes the forEach() method.

Anyway, that's a brief overview of common operations over Java and C++ hash map types, highlighting some of the similarities and differences between the two.

Happy coding!

Further Reading

How HashMap Works in Java

Optimizing a Hashing Strategy

Java Hashing: From Overriding HashCode to Mutable Objects

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook