簡體   English   中英

在 Java 中按鍵從 Map 中刪除元素的最快方法是什么?

[英]What's the quickest way to remove an element from a Map By Key in Java?

有一個Object的例子,提交的id是唯一的。

我假設 map 中有很多元素,從 map 中刪除 id = 1 示例的最快方法是什么。

public class Solution {

    @Data
    public static class Example {
        // unique key
        int    id;
        Object filed;
    }

    public static void main(String[] args) {
        // Suppose there are many elements in the map
        HashMap<Example, Object> map = new HashMap<>();
        int id = 1;
        Example example = new Example();
        example.setId(id);
        map.put(example, new Object());

        // How to quickly delete example of id = 1


        System.out.println(map);
    }

}

您必須覆蓋Example class 中的equalshashCode方法。 發布當您調用 map.remove(example) 時,它將刪除它。 在您的equalshashCode方法中,您必須使用字段id作為相等或比較因子。

class Example {
    
    @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Example)) return false;
    Example that = (Example) o;
    return id == that.id;
}

@Override
public int hashCode() {
    return Objects.hash(id);
}
}

注意:以上不是編譯代碼,只是一個片段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM