Java - How to create new Entry (key, value)

前端 未结 11 1529
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 09:55

I\'d like to create new item that similarly to Util.Map.Entry that will contain the structure key, value.

The problem is that

11条回答
  •  野性不改
    2020-11-27 10:12

    You can just implement the Map.Entry interface yourself:

    import java.util.Map;
    
    final class MyEntry implements Map.Entry {
        private final K key;
        private V value;
    
        public MyEntry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    
        @Override
        public K getKey() {
            return key;
        }
    
        @Override
        public V getValue() {
            return value;
        }
    
        @Override
        public V setValue(V value) {
            V old = this.value;
            this.value = value;
            return old;
        }
    }
    

    And then use it:

    Map.Entry entry = new MyEntry("Hello", 123);
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
    

提交回复
热议问题