HashMap is a collection that can manage a collection of elements that are a set of keys and values.
The following is output as a set of element name and atomic number.
import java.util.HashMap; //import
public class Sample {
public static void main(String[] args){
//The key is a string and the value is an integer
HashMap<String, Integer> map = new HashMap<String, Integer>();
String atom[] = {"hydrogen", "helium", "lithium", "beryllium"};
map.put(atom[0], 1); // .put()Store data in
map.put(atom[1], 2);
map.put(atom[2], 3);
map.put(atom[3], 4);
System.out.println("---Atomic number---");
for(String s:atom){
System.out.println(s + "Is" + map.get(s) + "Turn"); // .get()Get the value with
}
}
}
---Atomic number---
Hydrogen is number one
Helium is number 2
Lithium is number 3
Beryllium is number 4
| Method | function |
|---|---|
| get() | Returns the element of the specified key. |
| put() | Associate the key with the element. |
| remove() | Deletes the element with the specified key. |
| clear() | Erases all keys and elements. |
| containsKey() | Returns true if the specified key value exists, false otherwise. |
| isEmpty() | Returns true if there are no elements. |
| size() | Returns the number of elements. |
HashSet is a collection that can store data without duplication.
The following stores APPLE character by character and outputs it.
import java.util.HashSet;
public class Sample {
public static void main(String[] args){
HashSet<String> hs = new HashSet<String>(); //Generated as String type
hs.add("A"); //.add()Store data in
hs.add("P");
hs.add("P");
hs.add("L");
hs.add("E");
for(String s:hs){ //Display all with a special for statement
System.out.println(s);
}
}
}
Two Ps are stored, and since duplication has occurred, it is output only once.
P
A
E
L
| Method | function |
|---|---|
| add() | Add an element. |
| remove() | Deletes the specified element. |
| clear() | Erase all elements. |
| contains | Returns true if the specified element exists, false otherwise. |
| isEmpty() | Returns true if there are no elements. |
| size() | Returns the number of elements. |
Recommended Posts