Java EnumMap

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về lớp Java EnumMap và các hoạt động của nó với sự trợ giúp của các ví dụ.

Các EnumMaplớp học của khuôn khổ bộ sưu tập Java cung cấp một thực hiện bản đồ cho các yếu tố của một enum.

Trong EnumMap, các phần tử enum được sử dụng làm khóa . Nó thực hiện giao diện Bản đồ .

Trước khi chúng ta tìm hiểu về EnumMap, hãy nhớ biết về Java Enums .

Tạo EnumMap

Để tạo một bản đồ enum, java.util.EnumMaptrước tiên chúng ta phải nhập gói. Sau khi chúng tôi nhập gói, đây là cách chúng tôi có thể tạo bản đồ enum trong Java.

enum Size {
    SMALL, MEDIUM, LARGE, EXTRALARGE
}

EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);

Trong ví dụ trên, chúng ta đã tạo một bản đồ enum có tên là các kích thước .

Đây,

  • Size – keys of the enum that map to values
  • Integer – values of the enum map associated with the corresponding keys

Phương thức của EnumMap

Các EnumMaplớp học cung cấp phương pháp đó cho phép chúng tôi thực hiện các yếu tố khác nhau trên bản đồ enum.

Chèn các phần tử vào EnumMap

  • put() – inserts the specified key/value mapping (entry) to the enum map
  • putAll() – inserts all the entries of a specified map to this map

Ví dụ,

import java.util.EnumMap;

class Main {

    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {

        // Creating an EnumMap of the Size enum
        EnumMap<Size, Integer> sizes1 = new EnumMap<>(Size.class);

        // Using the put() Method
        sizes1.put(Size.SMALL, 28);
        sizes1.put(Size.MEDIUM, 32);
        System.out.println("EnumMap1: " + sizes1);

        EnumMap<Size, Integer> sizes2 = new EnumMap<>(Size.class);

        // Using the putAll() Method
        sizes2.putAll(sizes1);
        sizes2.put(Size.LARGE, 36);
        System.out.println("EnumMap2: " + sizes2);
    }
}

Đầu ra

EnumMap1: {SMALL=28, MEDIUM=32}
EnumMap2: {SMALL=28, MEDIUM=32, LARGE=36}

Trong ví dụ trên, chúng ta đã sử dụng putAll()phương thức để chèn tất cả các phần tử của bản đồ enum size1 vào bản đồ enum có kích thước2 .

Nó cũng có thể chèn các yếu tố từ các bản đồ khác như HashMapTreeMap, vv để một bản đồ enum sử dụng putAll(). Tuy nhiên, tất cả các bản đồ phải có cùng kiểu enum.

Truy cập các phần tử EnumMap

1. Sử dụng entrySet (), keySet () và các giá trị ()

  • entrySet() – returns a set of all the keys/values mapping (entry) of an enum map
  • keySet() – returns a set of all the keys of an enum map
  • values() – returns a set of all the values of an enum map

Ví dụ,

import java.util.EnumMap;

class Main {

    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {

        // Creating an EnumMap of the Size enum
        EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);
        sizes.put(Size.SMALL, 28);
        sizes.put(Size.MEDIUM, 32);
        sizes.put(Size.LARGE, 36);
        sizes.put(Size.EXTRALARGE, 40);
        System.out.println("EnumMap: " + sizes);

        // Using the entrySet() Method
        System.out.println("Key/Value mappings: " + sizes.entrySet());

        // Using the keySet() Method
        System.out.println("Keys: " + sizes.keySet());

        // Using the values() Method
        System.out.println("Values: " + sizes.values());
    }
}

Đầu ra

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}
Key/Value mappings: [SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40]
Keys: [SMALL, MEDIUM, LARGE, EXTRALARGE]
Values: [28, 32, 36, 40]

2. Sử dụng phương thức get ()

Các get()phương thức trả về giá trị gắn liền với phím chỉ định. Nó trả về nullnếu không tìm thấy khóa được chỉ định.

Ví dụ,

import java.util.EnumMap;

class Main {

    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {

        // Creating an EnumMap of the Size enum
        EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);
        sizes.put(Size.SMALL, 28);
        sizes.put(Size.MEDIUM, 32);
        sizes.put(Size.LARGE, 36);
        sizes.put(Size.EXTRALARGE, 40);
        System.out.println("EnumMap: " + sizes);

        // Using the get() Method
        int value = sizes.get(Size.MEDIUM);
        System.out.println("Value of MEDIUM: " + value);
    }
}

Đầu ra

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}
Value of MEDIUM: 32

Loại bỏ các phần tử EnumMap

  • remove(key) – returns and removes the entry associated with the specified key from the map
  • remove(key, value) – removes the entry from the map only if the specified key mapped to the specified value and return a boolean value

Ví dụ,

import java.util.EnumMap;

class Main {

    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {

        // Creating an EnumMap of the Size enum
        EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);
        sizes.put(Size.SMALL, 28);
        sizes.put(Size.MEDIUM, 32);
        sizes.put(Size.LARGE, 36);
        sizes.put(Size.EXTRALARGE, 40);
        System.out.println("EnumMap: " + sizes);

        // Using the remove() Method
        int value = sizes.remove(Size.MEDIUM);
        System.out.println("Removed Value: " + value);

        boolean result = sizes.remove(Size.SMALL, 28);
        System.out.println("Is the entry {SMALL=28} removed? " + result);

        System.out.println("Updated EnumMap: " + sizes);
    }
}

Đầu ra

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}
Removed Value: 32
Is the entry {SMALL=28} removed? True
Updated EnumMap: {LARGE=36, EXTRALARGE=40}

Thay thế các phần tử EnumMap

  • replace(key, value) – replaces the value associated with the specified key by the new value
  • replace(key, old, new) – replaces the old value with the new value only if the old value is already associated with the specified key
  • replaceAll(function) – replaces each value of the map with the result of the specified function
import java.util.EnumMap;

class Main {

    enum Size {
        SMALL, MEDIUM, LARGE, EXTRALARGE
    }
    public static void main(String[] args) {

        // Creating an EnumMap of the Size enum
        EnumMap<Size, Integer> sizes = new EnumMap<>(Size.class);
        sizes.put(Size.SMALL, 28);
        sizes.put(Size.MEDIUM, 32);
        sizes.put(Size.LARGE, 36);
        sizes.put(Size.EXTRALARGE, 40);
        System.out.println("EnumMap: " + sizes);

        // Using the replace() Method
        sizes.replace(Size.MEDIUM, 30);
        sizes.replace(Size.LARGE, 36, 34);
        System.out.println("EnumMap using replace(): " + sizes);

        // Using the replaceAll() Method
        sizes.replaceAll((key, oldValue) -> oldValue + 3);
        System.out.println("EnumMap using replaceAll(): " + sizes);
    }
}

Đầu ra

EnumMap: {SMALL=28, MEDIUM=32, LARGE=36, EXTRALARGE=40}
EnumMap using replace(): {SMALL=28, MEDIUM=30, LARGE=34, EXTRALARGE=40}
EnumMap using replaceAll(): {SMALL=31, MEDIUM=33, LARGE=37, EXTRALARGE=43}

Trong chương trình trên, hãy chú ý câu lệnh

sizes.replaceAll((key, oldValue) -> oldValue + 3);

Tại đây, phương thức này truy cập tất cả các mục của bản đồ. Sau đó, nó thay thế tất cả các giá trị bằng các giá trị mới được cung cấp bởi các biểu thức lambda .

Các phương pháp khác

MethodDecfscription
clone()Creates a copy of the EnumMap
containsKey()Searches the EnumMap for the specified key and returns a boolean result
containsValue()Searches the EnumMap for the specified value and returns a boolean result
size()Returns the size of the EnumMap
clear()Removes all the entries from the EnumMap

EnumSet Vs. EnumMap

Cả EnumSet và EnumMapclass đều cung cấp các cấu trúc dữ liệu để lưu trữ các giá trị enum. Tuy nhiên, tồn tại một số khác biệt lớn giữa chúng.

  • Enum set is represented internally as a sequence of bits, whereas the enum map is represented internally as arrays.
  • Enum set is created using its predefined methods like allOf()noneOf()of(), etc. However, an enum map is created using its constructor.

Giao diện có thể sao chép và nối tiếp hóa

Các EnumMaplớp cũng cụ Cloneablevà Serializablegiao diện.

Giao diện nhân bản

Nó cho phép EnumMaplớp tạo một bản sao của các thể hiện của lớp.

Giao diện có thể nối tiếp hóa

Bất cứ khi nào các đối tượng Java cần được truyền qua mạng, các đối tượng cần được chuyển đổi thành các bit hoặc byte. Điều này là do các đối tượng Java không thể được truyền qua mạng.

Các Serializablegiao diện cho phép các lớp học để được đăng. Điều này có nghĩa là các đối tượng của các lớp thực thi Serializablecó thể được chuyển đổi thành bit hoặc byte.









Gõ tìm kiếm nhanh...