简体   繁体   中英

How can I do search method using hashtable in java?

import java.util.Enumeration;
import java.util.Hashtable;

//@author fsociety 

public class HashFoo {

public static void main(String[] args) {
    HashFoo <String,String> student = new HashFoo <String,String>();

    student.put("1", "A");//Left side: Key , Right side: Value
    student.put("2", "B");//Left side: Key , Right side: Value
    student.put("3", "C");//Left side: Key , Right side: Value
    student.put("4", "D");//Left side: Key , Right side: Value
    student.put("5", "E");//Left side: Key , Right side: Value
    student.put("6", "F");//Left side: Key , Right side: Value
    student.put("7", "G");//Left side: Key , Right side: Value
    student.put("8", "H");//Left side: Key , Right side: Value

        System.out.println("Search this person 1 information: " + student.get("1"));//Get someone
        System.out.println("Is the person I wrote type of KEY: " + student.containsKey("2"));
        System.out.println("Is the person I wrote type of VALUE: " + student.containsValue("Z") + "\n");

    Enumeration enumerationValue = student.elements();
    Enumeration enumerationKeys = student.keys();
        System.out.println("Hash Table Values: "+"\n");

    while(enumerationValue.hasMoreElements() && enumerationKeys.hasMoreElements()){
        System.out.println(enumerationKeys.nextElement()+ " --> " + enumerationValue.nextElement() + "\n");
    }

        System.out.println("Is student hashtable empty: " + student.isEmpty());
        System.out.println("Hashtable size: " + student.size());

} 

}

I am new so I will learn hash with time. Now, I want to learn how can I do static search,insert,delete method in main. Also how can I store key-value in the array? Thank you in advance. Output Search this person 1 information: A Is the person I wrote type of KEY: true Is the person I wrote type of VALUE: false

Hash Table Values:

6 --> F

5 --> E

4 --> D

3 --> C

2 --> B

1 --> A

8 --> H

7 --> G

Is student hashtable empty: false Hashtable size: 8

I want search in this shape;

Output

1-Search: ..someone.. 2-Insert: ..someone.. 3-Delete: ..someone..

With HashMap, you only do this:

At the beginin of your code:

Map< String,String> student = new HashMap < String,String>();

and you get : put, get, contains, remove

You have several options:

to learn more, see this: difference between linkedhashmap, hashmap, map, hashtable

and this: Differences between HashMap and Hashtable?

If you want to keep your order, use LinkedHashMap instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM