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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Java String: A Complete Guide With Examples
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Import a Function/Module in Dataweave
  • Deploying Artemis Broker With SSL Enabled and Use AMQP

Trending

  • Memory-Optimized Tables: Implementation Strategies for SQL Server
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Designing for Sustainability: The Rise of Green Software
  • Designing AI Multi-Agent Systems in Java
  1. DZone
  2. Coding
  3. Java
  4. Custom Operators for Collections in Java

Custom Operators for Collections in Java

Learn how to use operator overloading in Java, using it's existing conventions.

By 
Peter Lawrey user avatar
Peter Lawrey
·
Sep. 21, 15 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
18.4K Views

Join the DZone community and get the full member experience.

Join For Free

Operator overloading is available in an number of languages.  Java has very limited operator overloading in it's support for the + operator for String types.

We can draw on the different ways other languages support operators, but can we have an implementation in Java that uses conventions that Java already uses?

Get, Set and Put Operations

A common example of operator overloading for collections is using the array notation a[b] to access the collection itself.  When getting this is straight forward as both List and Map have a get method and this is consistent with the JavaBean getXxx() naming convention.

List<String> text = ...

String s = text[2]; // text.get(2);


Map<String, MyType> map = ...

MyType mt = map["Hello"]; // map.get("Hello")


MyType mt = ...

String xxx = ...

String s = mt[xxx]; // mt.getXxx();

When it comes to setting a value based on an index or key, we have List.set(), Map.put() and setXxx() from JavaBeans. We could go three way to resolve this.

  1. Add a set method to Map.
  2. Use a convention which looks for a set or put method and complains if there is both.
  3. Default to set() but add an annotation which override it to put().
  4. We add a new special method to all collections for setting.

The simplest option to demonstrate is where the compiler chooses either set or put, though this is unlikely to be the best option.

text[2] = "Hi"; // text.set(2, "Hi");

map["Hello"] = "World"; // text.put("Hello", "World");

mt[xxx] = "Updated"; // mt.setXxx("Updated");

Add Operation

The add operations are more interesting as it could be used in combination.

List<Integer> nums =
AtomicInteger ai =

nums += 5; // nums.add(5);

ai += 5; // ai.addAndGet(5);

nums[1] += 5; // is it thread safe?

mt[xxx] += 5; // mt.addXxx(5);

The last example has the problem that a developer could unknowingly perform an unsafe operation on a thread safe collection.  If this was mapped to...

nums.set(1, nums.get(1) + 5)); // not thread safe

This is not thread safe.  Instead, we could map this to a lambda function.

nums.update(1, x -> x + 5); // could be thread safe

This could be made thread safe by the underlying List.

Similarly for Map, you can call compute

map["Hello"] += " !!";

Converts to 

map.compute("Hello", (k, v) -> v + " !!");

Conclusion

It may be possible to add operator support for object types with very little changes to existing code.  You could use existing conventions though you might find that the use of annotations is needed in some cases for more explicit control on how this works.

Operator (extension) Java (programming language)

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Java String: A Complete Guide With Examples
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • Import a Function/Module in Dataweave
  • Deploying Artemis Broker With SSL Enabled and Use AMQP

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!