📜  Java的散列

📅  最后修改于: 2021-10-27 16:58:30             🧑  作者: Mango

在散列中,有一个将键映射到某些值的散列函数。但是这些散列函数可能会导致冲突,即两个或多个键被映射到相同的值。链散列避免冲突。这个想法是让哈希表的每个单元格都指向一个具有相同哈希函数值的记录链表。

让我们创建一个哈希函数,这样我们的哈希表就有“N”个桶。
要将节点插入哈希表,我们需要找到给定键的哈希索引。它可以使用哈希函数计算。
示例:hashIndex = key % noOfBuckets

Insert :移动到上面计算出的hash索引对应的bucket,在链表末尾插入新节点。

删除:从hash表中删除一个节点,计算key的hash索引,移动到计算出的hash索引对应的bucket,搜索当前bucket中的list,找到并删除给定key的节点(如果找到) .

请参考Hashing |有关详细信息,请设置 2(单独链接)

在Java实现散列的方法

  1. 借助 HashTable(哈希的同步实现)
  2. // Java program to demonstrate working of HashTable
    import java.util.*;
      
    class GFG {
        public static void main(String args[])
        {
      
            // Create a HashTable to store 
            // String values corresponding to integer keys
            Hashtable
                hm = new Hashtable();
      
            // Input the values
            hm.put(1, "Geeks");
            hm.put(12, "forGeeks");
            hm.put(15, "A computer");
            hm.put(3, "Portal");
      
            // Printing the Hashtable
            System.out.println(hm);
        }
    }
    
    输出:
    {15=A computer, 3=Portal, 12=forGeeks, 1=Geeks}
    

  3. 借助 HashMap(一种非同步的更快的散列实现)
    // Java program to create HashMap from an array
    // by taking the elements as Keys and
    // the frequencies as the Values
      
    import java.util.*;
      
    class GFG {
      
        // Function to create HashMap from array
        static void createHashMap(int arr[])
        {
            // Creates an empty HashMap
            HashMap hmap = new HashMap();
      
            // Traverse through the given array
            for (int i = 0; i < arr.length; i++) {
      
                // Get if the element is present
                Integer c = hmap.get(arr[i]);
      
                // If this is first occurrence of element
                // Insert the element
                if (hmap.get(arr[i]) == null) {
                    hmap.put(arr[i], 1);
                }
      
                // If elements already exists in hash map
                // Increment the count of element by 1
                else {
                    hmap.put(arr[i], ++c);
                }
            }
      
            // Print HashMap
            System.out.println(hmap);
        }
      
        // Driver method to test above method
        public static void main(String[] args)
        {
            int arr[] = { 10, 34, 5, 10, 3, 5, 10 };
            createHashMap(arr);
        }
    }
    
    输出:
    {34=1, 3=1, 5=2, 10=3}
    

  4. 借助 LinkedHashMap(类似于 HashMap,但保持元素顺序)
    // Java program to demonstrate working of LinkedHashMap 
    import java.util.*; 
        
    public class BasicLinkedHashMap 
    { 
        public static void main(String a[]) 
        { 
            LinkedHashMap lhm = 
                           new LinkedHashMap(); 
            lhm.put("one", "practice.geeksforgeeks.org"); 
            lhm.put("two", "code.geeksforgeeks.org"); 
            lhm.put("four", "quiz.geeksforgeeks.org"); 
        
            // It prints the elements in same order  
            // as they were inserted     
            System.out.println(lhm); 
        
            System.out.println("Getting value for key 'one': " 
                                           + lhm.get("one")); 
            System.out.println("Size of the map: " + lhm.size()); 
            System.out.println("Is map empty? " + lhm.isEmpty()); 
            System.out.println("Contains key 'two'? "+  
                                      lhm.containsKey("two")); 
            System.out.println("Contains value 'practice.geeks"
            +"forgeeks.org'? "+ lhm.containsValue("practice"+ 
            ".geeksforgeeks.org")); 
            System.out.println("delete element 'one': " +  
                               lhm.remove("one")); 
            System.out.println(lhm); 
        } 
    } 
    
    输出:
    {one=practice.geeksforgeeks.org, two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}
    Getting value for key 'one': practice.geeksforgeeks.org
    Size of the map: 3
    Is map empty? false
    Contains key 'two'? true
    Contains value 'practice.geeksforgeeks.org'? true
    delete element 'one': practice.geeksforgeeks.org
    {two=code.geeksforgeeks.org, four=quiz.geeksforgeeks.org}
    

  5. 在 ConcurretHashMap 的帮助下(类似于 Hashtable,同步,但使用多个锁时速度更快)
    // Java program to demonstrate working of ConcurrentHashMap
      
    import java.util.concurrent.*;
    class ConcurrentHashMapDemo {
        public static void main(String[] args)
        {
            ConcurrentHashMap m = 
                       new ConcurrentHashMap();
            m.put(100, "Hello");
            m.put(101, "Geeks");
            m.put(102, "Geeks");
      
            // Printing the ConcurrentHashMap
            System.out.println("ConcurentHashMap: " + m);
      
            // Adding Hello at 101 key
            // This is already present in ConcurrentHashMap object
            // Therefore its better to use putIfAbsent for such cases
            m.putIfAbsent(101, "Hello");
      
            // Printing the ConcurrentHashMap
            System.out.println("\nConcurentHashMap: " + m);
      
            // Trying to remove entry for 101 key
            // since it is present
            m.remove(101, "Geeks");
      
            // Printing the ConcurrentHashMap
            System.out.println("\nConcurentHashMap: " + m);
      
            // replacing the value for key 101
            // from "Hello" to "For"
            m.replace(100, "Hello", "For");
      
            // Printing the ConcurrentHashMap
            System.out.println("\nConcurentHashMap: " + m);
        }
    }
    
    输出:

    ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}
    
    ConcurentHashMap: {100=Hello, 101=Geeks, 102=Geeks}
    
    ConcurentHashMap: {100=Hello, 102=Geeks}
    
    ConcurentHashMap: {100=For, 102=Geeks}
    

  6. 借助HashSet(类似于HashMap,但只维护key,不维护pair)
    // Java program to demonstrate working of HashSet
    import java.util.*;
      
    class Test {
        public static void main(String[] args)
        {
            HashSet h = new HashSet();
      
            // Adding elements into HashSet usind add()
            h.add("India");
            h.add("Australia");
            h.add("South Africa");
            h.add("India"); // adding duplicate elements
      
            // Displaying the HashSet
            System.out.println(h);
      
            // Checking if India is present or not
            System.out.println("\nHashSet contains India or not:"
                               + h.contains("India"));
      
            // Removing items from HashSet using remove()
            h.remove("Australia");
      
            // Printing the HashSet
            System.out.println("\nList after removing Australia:" + h);
      
            // Iterating over hash set items
            System.out.println("\nIterating over list:");
            Iterator i = h.iterator();
            while (i.hasNext())
                System.out.println(i.next());
        }
    }
    
    输出:
    [South Africa, Australia, India]
    
    HashSet contains India or not:true
    
    List after removing Australia:[South Africa, India]
    
    Iterating over list:
    South Africa
    India
    

  7. 借助 LinkedHashSet(类似于 LinkedHashMap,但只维护键,不维护对)
    // Java program to demonstrate working of LinkedHashSet
      
    import java.util.LinkedHashSet;   
    public class Demo  
    {   
        public static void main(String[] args)  
        {   
            LinkedHashSet linkedset =  
                               new LinkedHashSet();   
        
            // Adding element to LinkedHashSet   
            linkedset.add("A");   
            linkedset.add("B");   
            linkedset.add("C");   
            linkedset.add("D");  
        
            // This will not add new element as A already exists  
            linkedset.add("A");  
            linkedset.add("E");   
        
            System.out.println("Size of LinkedHashSet = " + 
                                        linkedset.size());   
            System.out.println("Original LinkedHashSet:" + linkedset);   
            System.out.println("Removing D from LinkedHashSet: " + 
                                linkedset.remove("D"));   
            System.out.println("Trying to Remove Z which is not "+ 
                                "present: " + linkedset.remove("Z"));   
            System.out.println("Checking if A is present=" +  
                                linkedset.contains("A")); 
            System.out.println("Updated LinkedHashSet: " + linkedset);   
        }   
    }   
    
    输出:
    Size of LinkedHashSet = 5
    Original LinkedHashSet:[A, B, C, D, E]
    Removing D from LinkedHashSet: true
    Trying to Remove Z which is not present: false
    Checking if A is present=true
    Updated LinkedHashSet: [A, B, C, E]
    
  8. 借助 TreeSet(实现 SortedSet 接口,对象按排序和升序存储)。
    // Java program to demonstrate working of TreeSet
      
    import java.util.*; 
        
    class TreeSetDemo { 
        public static void main(String[] args) 
        { 
            TreeSet ts1 = new TreeSet(); 
        
            // Elements are added using add() method 
            ts1.add("A"); 
            ts1.add("B"); 
            ts1.add("C"); 
        
            // Duplicates will not get insert 
            ts1.add("C"); 
        
            // Elements get stored in default natural 
            // Sorting Order(Ascending) 
            System.out.println("TreeSet: " + ts1); 
      
            // Checking if A is present or not
            System.out.println("\nTreeSet contains A or not:"
                               + ts1.contains("A"));
      
            // Removing items from TreeSet using remove()
            ts1.remove("A");
      
            // Printing the TreeSet
            System.out.println("\nTreeSet after removing A:" + ts1);
      
            // Iterating over TreeSet items
            System.out.println("\nIterating over TreeSet:");
            Iterator i = ts1.iterator();
            while (i.hasNext())
                System.out.println(i.next());
        }
    }
    

    输出:

    TreeSet: [A, B, C]
    
    TreeSet contains A or not:true
    
    TreeSet after removing A:[B, C]
    
    Iterating over TreeSet:
    B
    C
    

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程