📜  Java中的集合

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

Java中的集合

任何表示为单个单元的单个对象组称为对象的集合。在Java中,JDK 1.2 中定义了一个名为“集合框架”的单独框架,其中包含所有集合类和接口。

Collection 接口 ( Java.util.Collection ) 和 Map 接口 ( Java.util.Map ) 是Java集合类的两个主要“根”接口。

什么是框架?

框架是一组提供现成架构的类和接口。为了实现一个新特性或一个类,不需要定义一个框架。然而,一个最佳的面向对象设计总是包含一个具有类集合的框架,这样所有的类都执行相同类型的任务。

需要一个单独的收集框架

在引入集合框架(或 JDK 1.2 之前)之前,对Java对象(或集合)进行分组的标准方法是ArraysVectorsHashtables 。所有这些集合都没有通用接口。因此,尽管所有集合的主要目的是相同的,但所有这些集合的实现都是独立定义的,它们之间没有关联。而且,用户很难记住每个集合类中存在的所有不同的方法、语法和构造函数

让我们通过在哈希表和向量中添加元素的示例来理解这一点。

Java
// Java program to demonstrate
// why collection framework was needed
import java.io.*;
import java.util.*;
  
class CollectionDemo {
  
    public static void main(String[] args)
    {
        // Creating instances of the array,
        // vector and hashtable
        int arr[] = new int[] { 1, 2, 3, 4 };
        Vector v = new Vector();
        Hashtable h = new Hashtable();
  
        // Adding the elements into the
        // vector
        v.addElement(1);
        v.addElement(2);
  
        // Adding the element into the
        // hashtable
        h.put(1, "geeks");
        h.put(2, "4geeks");
  
        // Array instance creation requires [],
        // while Vector and hastable require ()
        // Vector element insertion requires addElement(),
        // but hashtable element insertion requires put()
  
        // Accessing the first element of the
        // array, vector and hashtable
        System.out.println(arr[0]);
        System.out.println(v.elementAt(0));
        System.out.println(h.get(1));
  
        // Array elements are accessed using [],
        // vector elements using elementAt()
        // and hashtable elements using get()
    }
}


Java
// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the ArrayList with
        // initial size n
        ArrayList al = new ArrayList();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            al.add(i);
  
        // Printing elements
        System.out.println(al);
  
        // Remove element at index 3
        al.remove(3);
  
        // Displaying the ArrayList
        // after deletion
        System.out.println(al);
  
        // Printing elements one by one
        for (int i = 0; i < al.size(); i++)
            System.out.print(al.get(i) + " ");
    }
}


Java
// Java program to demonstrate the
// working of LinkedList
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the LinkedList
        LinkedList ll = new LinkedList();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            ll.add(i);
  
        // Printing elements
        System.out.println(ll);
  
        // Remove element at index 3
        ll.remove(3);
  
        // Displaying the List
        // after deletion
        System.out.println(ll);
  
        // Printing elements one by one
        for (int i = 0; i < ll.size(); i++)
            System.out.print(ll.get(i) + " ");
    }
}


Java
// Java program to demonstrate the
// working of Vector
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the Vector
        Vector v = new Vector();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            v.add(i);
  
        // Printing elements
        System.out.println(v);
  
        // Remove element at index 3
        v.remove(3);
  
        // Displaying the Vector
        // after deletion
        System.out.println(v);
  
        // Printing elements one by one
        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + " ");
    }
}


Java
// Java program to demonstrate the
// working of a stack
import java.util.*;
public class GFG {
    
      // Main Method
    public static void main(String args[])
    {
        Stack stack = new Stack();
        stack.push("Geeks");
        stack.push("For");
        stack.push("Geeks");
        stack.push("Geeks");
  
        // Iterator for the stack
        Iterator itr = stack.iterator();
  
        // Printing the stack
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
  
        System.out.println();
  
        stack.pop();
  
        // Iterator for the stack
        itr = stack.iterator();
  
        // Printing the stack
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
    }
}


Java
// Java program to demonstrate the working of
// priority queue in Java
import java.util.*;
  
class GfG {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue pQueue = new PriorityQueue();
  
        // Adding items to the pQueue using add()
        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);
  
        // Printing the top element of PriorityQueue
        System.out.println(pQueue.peek());
  
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
  
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}


Java
// Java program to demonstrate the
// ArrayDeque class in Java
  
import java.util.*;
public class ArrayDequeDemo {
    public static void main(String[] args)
    {
        // Initializing an deque
        ArrayDeque de_que = new ArrayDeque(10);
  
        // add() method to insert
        de_que.add(10);
        de_que.add(20);
        de_que.add(30);
        de_que.add(40);
        de_que.add(50);
  
        System.out.println(de_que);
  
        // clear() method
        de_que.clear();
  
        // addFirst() method to insert the
        // elements at the head
        de_que.addFirst(564);
        de_que.addFirst(291);
  
        // addLast() method to insert the
        // elements at the tail
        de_que.addLast(24);
        de_que.addLast(14);
  
        System.out.println(de_que);
    }
}


Java
// Java program to demonstrate the
// working of a HashSet
import java.util.*;
  
public class HashSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating HashSet and
        // adding elements
        HashSet hs = new HashSet();
  
        hs.add("Geeks");
        hs.add("For");
        hs.add("Geeks");
        hs.add("Is");
        hs.add("Very helpful");
  
        // Traversing elements
        Iterator itr = hs.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}


Java
// Java program to demonstrate the
// working of a LinkedHashSet
import java.util.*;
  
public class LinkedHashSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating LinkedHashSet and
        // adding elements
        LinkedHashSet lhs = new LinkedHashSet();
  
        lhs.add("Geeks");
        lhs.add("For");
        lhs.add("Geeks");
        lhs.add("Is");
        lhs.add("Very helpful");
  
        // Traversing elements
        Iterator itr = lhs.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}


Java
// Java program to demonstrate the
// working of a TreeSet
import java.util.*;
  
public class TreeSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating TreeSet and
        // adding elements
        TreeSet ts = new TreeSet();
  
        ts.add("Geeks");
        ts.add("For");
        ts.add("Geeks");
        ts.add("Is");
        ts.add("Very helpful");
  
        // Traversing elements
        Iterator itr = ts.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}


Java
// Java program to demonstrate the
// working of a HashMap
import java.util.*;
  
public class HashMapDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating HashMap and
        // adding elements
        HashMap hm = new HashMap();
  
        hm.put(1, "Geeks");
        hm.put(2, "For");
        hm.put(3, "Geeks");
  
        // Finding the value for a key
        System.out.println("Value for 1 is " + hm.get(1));
  
        // Traversing through the HashMap
        for (Map.Entry e : hm.entrySet())
            System.out.println(e.getKey() + " " + e.getValue());
    }
}


输出:

1
1
geeks

正如我们所看到的,这些集合(Array、Vector 或 Hashtable)都没有实现标准的成员访问接口,程序员很难编写适用于各种集合的算法。另一个缺点是大多数“Vector”方法都是最终的,这意味着我们不能扩展“Vector”类来实现类似的 Collection。因此, Java开发人员决定提出一个通用接口来处理上述问题,并在 JDK 1.2 中引入了 Collection Framework,对遗留的 Vectors 和 Hashtables 进行了修改以符合 Collection Framework。

集合框架的优点:由于缺少集合框架导致了上述一系列缺点,以下是集合框架的优点。

  1. 一致的 API: API 有一组基本的接口,如CollectionSetListMap ,所有实现这些接口的类(ArrayList、LinkedList、Vector 等)都有一些通用的方法集。
  2. 减少编程工作:程序员不必担心集合的设计,而是可以专注于在他的程序中最好地使用它。因此,面向对象编程(即)抽象的基本概念已经成功实现。
  3. 提高程序速度和质量:通过提供有用的数据结构和算法的高性能实现来提高性能,因为在这种情况下,程序员不需要考虑特定数据结构的最佳实现。他可以简单地使用最佳实现来大幅提高他的算法/程序的性能。

集合框架的层次结构

实用程序包 (Java.util) 包含集合框架所需的所有类和接口。集合框架包含一个名为可迭代接口的接口,它提供迭代器来遍历所有集合。该接口由作为集合框架的根的主集合接口扩展。所有的集合都扩展了这个集合接口,从而扩展了迭代器的属性和这个接口的方法。下图说明了集合框架的层次结构。

集合-框架-层次结构

在了解上述框架中的不同组件之前,我们先来了解一个类和一个接口。

  • 类是用户定义的蓝图或原型,从中创建对象。它表示一种类型的所有对象共有的一组属性或方法。
  • 接口和类一样,接口可以有方法和变量,但是接口中声明的方法默认是抽象的(只有方法签名,没有主体)。接口指定一个类必须做什么而不是如何做。这是班级的蓝图。

集合接口的方法

该接口包含各种方法,所有实现该接口的集合都可以直接使用这些方法。他们是:

Method

Description

add(Object)This method is used to add an object to the collection.
addAll(Collection c)This method adds all the elements in the given collection to this collection.
clear()This method removes all of the elements from this collection.
contains(Object o)This method returns true if the collection contains the specified element.
containsAll(Collection c)This method returns true if the collection contains all of the elements in the given collection.
equals(Object o)This method compares the specified object with this collection for equality.
hashCode()This method is used to return the hash code value for this collection.
isEmpty()This method returns true if this collection contains no elements.
iterator()This method returns an iterator over the elements in this collection.
max() 
 
This method is used to return the maximum value present in the collection.
parallelStream()This method returns a parallel Stream with this collection as its source.
remove(Object o)This method is used to remove the given object from the collection. If there are duplicate values, then this method removes the first occurrence of the object.
removeAll(Collection c)This method is used to remove all the objects mentioned in the given collection from the collection.
removeIf(Predicate filter)This method is used to remove all the elements of this collection that satisfy the given predicate.
retainAll(Collection c)This method is used to retain only the elements in this collection that are contained in the specified collection.
size()This method is used to return the number of elements in the collection.
spliterator()This method is used to create a Spliterator over the elements in this collection.
stream()This method is used to return a sequential Stream with this collection as its source.
toArray()This method is used to return an array containing all of the elements in this collection.

扩展集合接口的接口

集合框架包含多个接口,其中每个接口都用于存储特定类型的数据。以下是框架中存在的接口。

1. 可迭代接口:这是整个集合框架的根接口。集合接口扩展了可迭代接口。因此,本质上,所有的接口和类都实现了这个接口。这个接口的主要功能是为集合提供一个迭代器。因此,该接口只包含一个抽象方法,即迭代器。它返回

2、集合接口:该接口扩展了可迭代接口,由集合框架中的所有类实现。该接口包含每个集合的所有基本方法,例如向集合中添加数据、删除数据、清除数据等。所有这些方法都在此接口中实现,因为这些方法由所有类实现,而与它们的样式无关的实施。而且,在这个接口中拥有这些方法可以确保方法的名称对于所有集合都是通用的。因此,简而言之,我们可以说这个接口为实现集合类奠定了基础。

3.列表接口:这是集合接口的子接口。该接口专用于列表类型的数据,我们可以在其中存储对象的所有有序集合。这也允许其中存在重复数据。这个列表接口由各种类实现,如 ArrayList、Vector、Stack 等。由于所有子类都实现了列表,我们可以使用这些类中的任何一个来实例化列表对象。例如,

实现 List 接口的类如下:

A. ArrayList: ArrayList 为我们提供了Java中的动态数组。虽然,它可能比标准数组慢,但在需要对数组进行大量操作的程序中很有帮助。如果从集合中删除对象,如果集合增长或缩小,则 ArrayList 的大小会自动增加。 Java ArrayList 允许我们随机访问列表。 ArrayList 不能用于原始类型,例如 int、char 等。对于这种情况,我们需要一个包装类。让我们通过以下示例来了解 ArrayList:

Java

// Java program to demonstrate the
// working of ArrayList
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the ArrayList with
        // initial size n
        ArrayList al = new ArrayList();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            al.add(i);
  
        // Printing elements
        System.out.println(al);
  
        // Remove element at index 3
        al.remove(3);
  
        // Displaying the ArrayList
        // after deletion
        System.out.println(al);
  
        // Printing elements one by one
        for (int i = 0; i < al.size(); i++)
            System.out.print(al.get(i) + " ");
    }
}
输出:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

B. LinkedList: LinkedList 类是 LinkedList 数据结构的实现,它是一种线性数据结构,其中元素不存储在连续的位置,每个元素都是具有数据部分和地址部分的单独对象。元素使用指针和地址链接。每个元素称为一个节点。让我们通过以下示例来了解 LinkedList:

Java

// Java program to demonstrate the
// working of LinkedList
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the LinkedList
        LinkedList ll = new LinkedList();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            ll.add(i);
  
        // Printing elements
        System.out.println(ll);
  
        // Remove element at index 3
        ll.remove(3);
  
        // Displaying the List
        // after deletion
        System.out.println(ll);
  
        // Printing elements one by one
        for (int i = 0; i < ll.size(); i++)
            System.out.print(ll.get(i) + " ");
    }
}
输出:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

C.向量:向量为我们提供了Java中的动态数组。虽然,它可能比标准数组慢,但在需要对数组进行大量操作的程序中很有帮助。这在实现方面与 ArrayList 相同。但是,vector 和 ArrayList 之间的主要区别在于 Vector 是同步的,而 ArrayList 是非同步的。让我们通过一个例子来理解 Vector:

Java

// Java program to demonstrate the
// working of Vector
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String[] args)
    {
  
        // Declaring the Vector
        Vector v = new Vector();
  
        // Appending new elements at
        // the end of the list
        for (int i = 1; i <= 5; i++)
            v.add(i);
  
        // Printing elements
        System.out.println(v);
  
        // Remove element at index 3
        v.remove(3);
  
        // Displaying the Vector
        // after deletion
        System.out.println(v);
  
        // Printing elements one by one
        for (int i = 0; i < v.size(); i++)
            System.out.print(v.get(i) + " ");
    }
}
输出:
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5

D. Stack Stack 类建模和实现 Stack 数据结构。该类基于后进先出的基本原则。除了基本的 push 和 pop 操作外,该类还提供了 empty、search 和 peek 三个功能。该类也可以称为 Vector 的子类。让我们通过一个例子来理解堆栈:

Java

// Java program to demonstrate the
// working of a stack
import java.util.*;
public class GFG {
    
      // Main Method
    public static void main(String args[])
    {
        Stack stack = new Stack();
        stack.push("Geeks");
        stack.push("For");
        stack.push("Geeks");
        stack.push("Geeks");
  
        // Iterator for the stack
        Iterator itr = stack.iterator();
  
        // Printing the stack
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
  
        System.out.println();
  
        stack.pop();
  
        // Iterator for the stack
        itr = stack.iterator();
  
        // Printing the stack
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
    }
}
输出:
Geeks For Geeks Geeks 
Geeks For Geeks

注意: Stack 是 Vector 的子类,也是遗留类。它是线程安全的,在不需要线程安全的环境中可能会产生开销。 Stack 的替代方法是使用 ArrayDequeue,它不是线程安全的,并且具有更快的数组实现。

4.队列接口顾名思义,队列接口维护 FIFO(先进先出)顺序,类似于现实世界的队列行。此接口专用于存储元素顺序重要的所有元素。例如,每当我们尝试预订门票时,门票都会以先到先得的方式出售。因此,请求首先到达队列的人将获得票。有各种各样的类,如 PriorityQueue、ArrayDeque 等。由于所有这些子类都实现了队列,我们可以使用这些类中的任何一个来实例化队列对象。例如,

队列接口最常用的实现是 PriorityQueue。优先级队列:当对象应该基于优先级进行处理时,使用优先级队列。众所周知,队列遵循先进先出算法,但有时需要根据优先级对队列中的元素进行处理,在这些情况下使用此类。 PriorityQueue 基于优先级堆。优先级队列的元素按照自然顺序排序,或者由队列构造时提供的 Comparator 排序,具体取决于使用的构造函数。让我们通过一个例子来理解优先级队列:

Java

// Java program to demonstrate the working of
// priority queue in Java
import java.util.*;
  
class GfG {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating empty priority queue
        PriorityQueue pQueue = new PriorityQueue();
  
        // Adding items to the pQueue using add()
        pQueue.add(10);
        pQueue.add(20);
        pQueue.add(15);
  
        // Printing the top element of PriorityQueue
        System.out.println(pQueue.peek());
  
        // Printing the top element and removing it
        // from the PriorityQueue container
        System.out.println(pQueue.poll());
  
        // Printing the top element again
        System.out.println(pQueue.peek());
    }
}
输出:
10
10
15

5. Deque Interface 这是队列数据结构的一个非常细微的变化。双端队列,也称为双端队列,是一种数据结构,我们可以在其中添加和删除队列两端的元素。该接口扩展了队列接口。实现这个接口的类是 ArrayDeque。由于 ArrayDeque 类实现了 Deque 接口,我们可以用这个类实例化一个双端队列对象。例如,

实现双端队列接口的类是 ArrayDeque。

ArrayDeque:集合框架中实现的 ArrayDeque 类为我们提供了一种应用 resizable-array 的方法。这是一种特殊的数组,它可以增长并允许用户从队列的两侧添加或删除元素。数组双端队列没有容量限制,它们会根据需要增长以支持使用。让我们通过一个例子来理解 ArrayDeque:

Java

// Java program to demonstrate the
// ArrayDeque class in Java
  
import java.util.*;
public class ArrayDequeDemo {
    public static void main(String[] args)
    {
        // Initializing an deque
        ArrayDeque de_que = new ArrayDeque(10);
  
        // add() method to insert
        de_que.add(10);
        de_que.add(20);
        de_que.add(30);
        de_que.add(40);
        de_que.add(50);
  
        System.out.println(de_que);
  
        // clear() method
        de_que.clear();
  
        // addFirst() method to insert the
        // elements at the head
        de_que.addFirst(564);
        de_que.addFirst(291);
  
        // addLast() method to insert the
        // elements at the tail
        de_que.addLast(24);
        de_que.addLast(14);
  
        System.out.println(de_que);
    }
}
输出:
[10, 20, 30, 40, 50]
[291, 564, 24, 14]

6.集合接口集合是对象的无序集合,其中不能存储重复值。当我们希望避免重复对象并希望仅存储唯一对象时使用此集合。这个集合接口由各种类实现,如 HashSet、TreeSet、LinkedHashSet 等。由于所有子类都实现了集合,我们可以使用这些类中的任何一个来实例化集合对象。例如,

以下是实现 Set 接口的类:

A. HashSet: HashSet 类是哈希表数据结构的固有实现。我们插入到 HashSet 中的对象不保证以相同的顺序插入。对象是根据它们的哈希码插入的。此类还允许插入 NULL 元素。让我们通过一个例子来理解 HashSet:

Java

// Java program to demonstrate the
// working of a HashSet
import java.util.*;
  
public class HashSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating HashSet and
        // adding elements
        HashSet hs = new HashSet();
  
        hs.add("Geeks");
        hs.add("For");
        hs.add("Geeks");
        hs.add("Is");
        hs.add("Very helpful");
  
        // Traversing elements
        Iterator itr = hs.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
输出:
Very helpful
Geeks
For
Is

B. LinkedHashSet LinkedHashSet 与 HashSet 非常相似。不同之处在于它使用双向链表来存储数据并保留元素的顺序。让我们通过一个例子来理解 LinkedHashSet:

Java

// Java program to demonstrate the
// working of a LinkedHashSet
import java.util.*;
  
public class LinkedHashSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating LinkedHashSet and
        // adding elements
        LinkedHashSet lhs = new LinkedHashSet();
  
        lhs.add("Geeks");
        lhs.add("For");
        lhs.add("Geeks");
        lhs.add("Is");
        lhs.add("Very helpful");
  
        // Traversing elements
        Iterator itr = lhs.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
输出:
Geeks
For
Is
Very helpful

7Sorted Set界面这个界面和set界面很相似。唯一的区别是这个接口有额外的方法来维护元素的顺序。 sorted set 接口扩展了 set 接口,用于处理需要排序的数据。实现这个接口的类是TreeSet。由于这个类实现了 SortedSet,我们可以用这个类实例化一个 SortedSet 对象。例如,

实现排序集接口的类是TreeSet。 TreeSet: TreeSet 类使用树进行存储。无论是否提供显式比较器,元素的顺序都由一个集合使用它们的自然顺序来维护。这必须与equals一致才能正确实现Set接口。它也可以通过在集合创建时提供的 Comparator 进行排序,具体取决于使用的构造函数。让我们通过一个例子来理解 TreeSet:

Java

// Java program to demonstrate the
// working of a TreeSet
import java.util.*;
  
public class TreeSetDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating TreeSet and
        // adding elements
        TreeSet ts = new TreeSet();
  
        ts.add("Geeks");
        ts.add("For");
        ts.add("Geeks");
        ts.add("Is");
        ts.add("Very helpful");
  
        // Traversing elements
        Iterator itr = ts.iterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
输出:
For
Geeks
Is
Very helpful

8. Map 接口 map 是一种支持数据键值对映射的数据结构。该接口不支持重复键,因为同一个键不能有多个映射。如果有数据并且我们希望基于键执行操作,则映射很有用。该地图接口由各种类实现,如 HashMap、TreeMap 等。由于所有子类都实现了地图,我们可以使用这些类中的任何一个来实例化地图对象。例如,

Map 接口的常用实现是 HashMap。 HashMap HashMap提供Java Map接口的基本实现。它将数据存储在(键,值)对中。要访问 HashMap 中的值,我们必须知道它的键。 HashMap 使用一种称为散列的技术。散列是一种将大字符串转换为代表相同字符串的小字符串的技术,以便索引和搜索操作更快。 HashSet 在内部也使用 HashMap。让我们通过一个例子来理解 HashMap:

Java

// Java program to demonstrate the
// working of a HashMap
import java.util.*;
  
public class HashMapDemo {
    
      // Main Method
    public static void main(String args[])
    {
        // Creating HashMap and
        // adding elements
        HashMap hm = new HashMap();
  
        hm.put(1, "Geeks");
        hm.put(2, "For");
        hm.put(3, "Geeks");
  
        // Finding the value for a key
        System.out.println("Value for 1 is " + hm.get(1));
  
        // Traversing through the HashMap
        for (Map.Entry e : hm.entrySet())
            System.out.println(e.getKey() + " " + e.getValue());
    }
}
输出:
Value for 1 is Geeks
1 Geeks
2 For
3 Geeks

您应该在Java集合中学习什么?

  • 列表接口
    • 抽象列表类
    • 抽象顺序列表类
    • 数组列表
    • 向量类
    • 堆栈类
    • 链表类
  • 队列接口
    • 阻塞队列接口
    • 抽象队列类
    • 优先队列类
    • PriorityBlockingQueue 类
    • ConcurrentLinkedQueue 类
    • ArrayBlockingQueue 类
    • 延迟队列类
    • LinkedBlockingQueue 类
    • 链接传输队列
  • 双端队列接口
    • BlockingDeque 接口
    • ConcurrentLinkedDeque 类
    • ArrayDeque 类
  • 设置界面
    • 抽象集类
    • CopyOnWriteArraySet 类
    • 枚举集类
    • ConcurrentHashMap 类
    • HashSet 类
    • LinkedHashSet 类
  • 排序集接口
    • NavigableSet 接口
    • 树集
    • ConcurrentSkipListSet 类
  • 地图界面
    • 排序地图接口
    • 导航地图接口
    • ConcurrentMap 接口
    • 树图类
    • 抽象地图类
    • ConcurrentHashMap 类
    • EnumMap 类
    • HashMap 类
    • IdentityHashMap 类
    • LinkedHashMap 类
    • 哈希表类
    • 属性类
  • 其他重要概念
    • 如何将 HashMap 转换为 ArrayList
    • 从列表中随机选择项目
    • 如何将集合中的所有项目添加到 ArrayList
    • Java映射到列表的转换
    • 数组到 ArrayList 的转换
    • ArrayList 到数组的转换
    • Array 和 ArrayList 的区别