📜  Java中的抽象映射

📅  最后修改于: 2022-05-13 01:55:02.433000             🧑  作者: Mango

Java中的抽象映射

AbstractMap类是Java集合框架的一部分。它直接实现了 Map 接口来为其提供一个结构,这样可以使进一步的实现更容易。顾名思义,AbstractMap 根据定义是一个抽象类,因此它不能用于创建对象。从 AbstractMap 继承的具体类可用于创建对象。

宣言:

public abstract class AbstractMap extends Object, implements Map

这里, K是键类型, V是值类型。

AbstractMap 的层次结构

Java 中的 AbstractMap 层次结构

该类实现了 Map 接口并扩展了 Object 类。

AbstractMap 的构造函数

Constructor

Definition

protected AbstractMap()This constructor cannot be used for creating objects. This constructor exists so that the inheriting classes can invoke it, this invocation is implicit.

基本操作

1. 添加元素

要向 AbstractMap 添加元素,我们使用 put() 方法。请注意,该方法实际上不是 AbstractMap 类型,而是一个扩展类,对此对象的引用是 AbstractMap 类型。映射的条目是键值对类型。这里的key是Integer类型的,value是String类型的,这个是在实例化对象的时候提到的。

Java
// Java Program to demonstrate adding
// elements to the AbstractMap
  
import java.util.*;
  
public class AddElements {
  
    public static void main(String[] args)
    {
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        // Adding values to the AbstractMap
        // Note that we do not create an object of
        // AbstractMap
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "an");
        absMap.put(4, "AbstractMap");
  
        // Displaying the mappings using
        // entrySet() to get the set view
        System.out.println("The Set view of the mappings:");
        System.out.println(absMap.entrySet());
    }
}


Java
// Java Program to demonstrate removing
// elements from the AbstractMap
  
import java.util.*;
  
public class RemoveElements {
  
    public static void main(String[] args)
    {
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "an");
        absMap.put(4, "AbstractMap");
  
        // Displaying the mappings
        System.out.println("Mappings of the AbstractMap:");
        System.out.println(absMap);
  
        // Removing an entry using the remove() method
        absMap.remove(1);
  
        // Displaying the mappings
        System.out.println("Mappings of the AbstractMap:");
        System.out.println(absMap);
  
        // Clearing the whole map using clear()
        absMap.clear();
  
        // Displaying the mappings
        System.out.println("\nThe Set view of the mappings:");
        System.out.println(absMap);
    }
}


Java
// Java Program to demonstrate replacing
// elements of AbstractMap
  
import java.util.AbstractMap;
import java.util.HashMap;
  
public class ReplaceElements {
  
    public static void main(String[] args)
    {
  
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        // Adding values to the AbstractMap
        // Note that we do not create an object of
        // AbstractMap
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "a");
        absMap.put(4, "AbstractMap");
  
        // Displaying the mappings
        System.out.println("Mappings of the AbstractMap:");
        System.out.println(absMap);
  
        // Replacing the mapping associated to 3
        absMap.replace(3, "an");
  
        // Displaying the mappings
        System.out.println("\nMappings of the AbstractMap:");
        System.out.println(absMap);
    }
}


Java
// Java Program to demonstrate
// traversing AbstractMap
  
import java.util.*;
  
public class Traversing {
  
    public static void main(String[] args)
    {
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        // Adding values to the AbstractMap
        // Note that we do not create an object of
        // AbstractMap
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "a");
        absMap.put(4, "AbstractMap");
  
        // METHOD 1
        // Iterate over the map using entrySet()
        // which returns a collection view of the map
  
        System.out.println("Using the entrySet() method");
  
        for (AbstractMap.Entry entry :
             absMap.entrySet()) {
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
  
        // METHOD 2
        // Iterate over the map using the Iterator interface
  
        System.out.println(
            "\nUsing the Iterator interface");
  
        Iterator itr = absMap.keySet().iterator();
        while (itr.hasNext()) {
            int key = itr.next();
            System.out.println("Key = " + key
                               + ", Value =  "
                               + absMap.get(key));
        }
    }
}


输出
The Set view of the mappings:
[1=This, 2=is, 3=an, 4=AbstractMap]

2. 删除元素

我们可以使用 remove() 方法从 AbstractMap 中删除映射。 remove 的语法是

mapName.remove(Object key);

这将删除映射到指定键的值。我们可以使用 clear() 方法清除整个 AbstractMap,如下所示。

Java

// Java Program to demonstrate removing
// elements from the AbstractMap
  
import java.util.*;
  
public class RemoveElements {
  
    public static void main(String[] args)
    {
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "an");
        absMap.put(4, "AbstractMap");
  
        // Displaying the mappings
        System.out.println("Mappings of the AbstractMap:");
        System.out.println(absMap);
  
        // Removing an entry using the remove() method
        absMap.remove(1);
  
        // Displaying the mappings
        System.out.println("Mappings of the AbstractMap:");
        System.out.println(absMap);
  
        // Clearing the whole map using clear()
        absMap.clear();
  
        // Displaying the mappings
        System.out.println("\nThe Set view of the mappings:");
        System.out.println(absMap);
    }
}
输出
Mappings of the AbstractMap:
{1=This, 2=is, 3=an, 4=AbstractMap}
Mappings of the AbstractMap:
{2=is, 3=an, 4=AbstractMap}

The Set view of the mappings:
{}

3. 替换条目

我们可以使用 replace() 方法替换与键关联的值,如下所示。

Java

// Java Program to demonstrate replacing
// elements of AbstractMap
  
import java.util.AbstractMap;
import java.util.HashMap;
  
public class ReplaceElements {
  
    public static void main(String[] args)
    {
  
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        // Adding values to the AbstractMap
        // Note that we do not create an object of
        // AbstractMap
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "a");
        absMap.put(4, "AbstractMap");
  
        // Displaying the mappings
        System.out.println("Mappings of the AbstractMap:");
        System.out.println(absMap);
  
        // Replacing the mapping associated to 3
        absMap.replace(3, "an");
  
        // Displaying the mappings
        System.out.println("\nMappings of the AbstractMap:");
        System.out.println(absMap);
    }
}
输出
Mappings of the AbstractMap:
{1=This, 2=is, 3=a, 4=AbstractMap}

Mappings of the AbstractMap:
{1=This, 2=is, 3=an, 4=AbstractMap}

4. 穿越

遍历 AbstractMap 有多种方式,我们在下面给出的代码中讨论两种方式。第一种方法是使用 entrySet() 方法,该方法返回地图的集合视图。可以通过使用 for each 循环来迭代此视图。方法getKey()返回键, getValue()返回关联的值。第二种方法是使用 Iterator 接口。我们使用 keySet() 方法在键集上创建一个迭代器。此迭代器用于使用 next() 方法迭代映射,该方法返回映射中的下一个条目。

Java

// Java Program to demonstrate
// traversing AbstractMap
  
import java.util.*;
  
public class Traversing {
  
    public static void main(String[] args)
    {
        // Since AbstractMap is an abstract class
        // create object using HashMap
        AbstractMap absMap
            = new HashMap();
  
        // Adding values to the AbstractMap
        // Note that we do not create an object of
        // AbstractMap
        absMap.put(1, "This");
        absMap.put(2, "is");
        absMap.put(3, "a");
        absMap.put(4, "AbstractMap");
  
        // METHOD 1
        // Iterate over the map using entrySet()
        // which returns a collection view of the map
  
        System.out.println("Using the entrySet() method");
  
        for (AbstractMap.Entry entry :
             absMap.entrySet()) {
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
  
        // METHOD 2
        // Iterate over the map using the Iterator interface
  
        System.out.println(
            "\nUsing the Iterator interface");
  
        Iterator itr = absMap.keySet().iterator();
        while (itr.hasNext()) {
            int key = itr.next();
            System.out.println("Key = " + key
                               + ", Value =  "
                               + absMap.get(key));
        }
    }
}
输出
Using the entrySet() method
Key = 1, Value = This
Key = 2, Value = is
Key = 3, Value = a
Key = 4, Value = AbstractMap

Using the Iterator interface
Key = 1, Value =  This
Key = 2, Value =  is
Key = 3, Value =  a
Key = 4, Value =  AbstractMap

继承类

1.哈希映射

HashMap 类是 Map 接口的基本实现,它存储键值对。 HashMap 是 Hashtable 的基本 Map 实现,但 HashMap 是非同步的。 HashMap 的元素顺序未定义。 HashMap 为插入、删除、遍历和操作的基本操作提供恒定的时间性能。

句法:

HashMap< ? , ? > hmName = new HashMap< ? , ? >();

2. IdentityHashMap

IdentityHashMap 是 Map 的 Hashtable 实现,但它使用引用相等而不是对象相等。也就是说 IdentityHashMap 违反了地图的基本规则,因此它不是通用地图,它是为罕见场景保留的。在 IdentityHashMap 中,任何两个对象 o1 和 o2 相等当且仅当 o1==o2 即 o1 和 o2 的引用相同。

句法:

IdentityHashMap< ? , ? > ihmName = new IdentityHashMap< ? , ? >();

3.弱HashMap

WeakHashMap 是使用弱键的 Map 接口的 Hashtable 实现。当 WeakHashMap 中的键不再正常使用时,它会被自动丢弃。这意味着映射的存在不会阻止密钥被垃圾收集。 WeakHashMap 是一个未同步的类。

句法:

WeakHashMap< ? , ? > whmName = new WeakHashMap< ? , ? >();

4. 树状图

TreeMap 类是基于红黑树的 NavigableMap 实现。 TreeMap 元素按自然顺序或按构建时提供的 Comparator 排序。

句法:

TreeMap< ? , ? > tmName = new TreeMap< ? , ? >();

5.枚举映射

EnumMap 是 Map 接口的特殊实现。 EnumMap 的键是枚举类型。所有的键都必须是相同的枚举,无论是显式定义还是隐式定义,在构造时指定。 EnumMap 在内部表示为一个数组,它非常紧凑和高效。

句法:

EnumMap< enumName, ? > emName = new EnumMap< enumName, ? >();

6. ConcurrentHashMap

ConcurrentHashMap 是一个 Hashtable 实现,它通过检索和更新操作支持完全并发。该类与Hashtable类高度兼容,包含了Hashtable的所有对应方法。尽管操作是线程安全的,但没有适当的锁定机制,因此检索可以重叠更新。因此,检索操作反映了最近完成的更新操作。

句法:

ConcurrentHashMap< ? , ? > chmName = new ConcurrentHashMap< ? , ? >();

7. ConcurrentSkipListMap

ConcurrentSkipListMap 是 ConcurrentNavigableMap 接口的可扩展实现。 ConcurrentSkipListMap 中的键按自然顺序或在构造对象时使用 Comparator 进行排序。 ConcurrentSkipListMap 的插入、删除和搜索操作的预期时间成本为 log n。它是一个线程安全的类,因此所有基本操作都可以并发完成。

句法:

ConcurrentSkipListMap< ? , ? > cslmName = new ConcurrentSkipListMap< ? , ? >();

AbstractMap 的方法

METHOD

DESCRIPTION

clear()Removes all of the mappings from this map (optional operation).
clone()Returns a shallow copy of this AbstractMap instance: the keys and values themselves are not cloned.
containsKey​(Object key)Returns true if this map contains a mapping for the specified key.
containsValue​(Object value)Returns true if this map maps one or more keys to the specified value.
equals​(Object o)Compares the specified object with this map for equality.
get​(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
hashCode() Returns the hash code value for this map.
isEmpty()Returns true if this map contains no key-value mappings.
keySet() Returns a Set view of the keys contained in this map.
put​(K key, V value) Associates the specified value with the specified key in this map (optional operation).
putAll​(Map m) Copies all of the mappings from the specified map to this map (optional operation).
remove​(Object key) Removes the mapping for a key from this map if it is present (optional operation).
size() Returns the number of key-value mappings in this map.
toString() Returns a string representation of this map.
values() Returns a Collection view of the values contained in this map.

在接口Java.util.Map 中声明的方法

METHOD

DESCRIPTION

compute​(K key, BiFunction remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
computeIfAbsent​(K key, Function mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
computeIfPresent​(K key, BiFunction remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
entrySet()Returns a Set view of the mappings contained in this map.
forEach​(BiConsumer action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault​(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
merge​(K key, V value, BiFunction remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
putIfAbsent​(K key, V value)If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove​(Object key, Object value)Removes the entry for the specified key only if it is currently mapped to the specified value.
replace​(K key, V value)Replaces the entry for the specified key only if it is currently mapped to some value.
replace​(K key, V oldValue, V newValue)Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll​(BiFunction function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.