Creating a Map with Integer Keys and Point2D Values in Java

Nov 19, 2025 · Programming · 12 views · 7.8

Keywords: Java | Map | HashMap | Point2D | Generics

Abstract: This article provides a comprehensive guide on creating and manipulating a Map in Java that stores integer keys and Point2D values. It covers the use of generics for type safety, basic operations such as insertion, access, and iteration, and alternative initialization methods. Rewritten code examples are included to illustrate key concepts in a step-by-step manner.

Introduction

In Java, the Map interface from the java.util package is a collection that stores key-value pairs, where each key is unique. This article focuses on creating a Map that uses integers as keys and Point2D.Double objects as values, addressing a common programming task.

Creating a Typed Map

To ensure type safety, generics are essential. For a Map with integer keys and Point2D values, declare it as follows:

import java.util.HashMap;
import java.util.Map;
import java.awt.geom.Point2D;

Map<Integer, Point2D.Double> pointMap = new HashMap<>();

The diamond operator <> allows the compiler to infer the type arguments. Note that Point2D is an abstract class, so we use Point2D.Double for instantiation.

Adding Elements

Use the put method to add key-value pairs:

pointMap.put(1, new Point2D.Double(50.0, 50.0));
pointMap.put(2, new Point2D.Double(100.0, 100.0));

If a key already exists, put updates the value.

Accessing and Iterating

To retrieve a value, use get:

Point2D.Double point = pointMap.get(1);

For iteration, use entrySet:

for (Map.Entry<Integer, Point2D.Double> entry : pointMap.entrySet()) {
    Integer key = entry.getKey();
    Point2D.Double value = entry.getValue();
    System.out.println("Key: " + key + ", Value: " + value);
}

Other Operations

Common methods include remove to delete entries, containsKey to check for keys, and size to get the number of entries. From Java 8, methods like getOrDefault and putIfAbsent are available for safer operations.

Alternative Initialization

For static or initial values, you can use an anonymous subclass with an instance initializer block, though it's less efficient:

Map<Integer, Point2D.Double> initialMap = new HashMap<Integer, Point2D.Double>() {
    {
        put(1, new Point2D.Double(50.0, 50.0));
        put(2, new Point2D.Double(100.0, 100.0));
    }
};

This approach is useful for small, fixed maps but should be avoided for large or dynamic ones due to performance overhead.

Conclusion

Using generics in Map creation ensures type safety and clarity. The HashMap implementation provides efficient operations for most use cases. Always prefer typed collections to raw types for better code quality.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.