HashMap和TreeMap

This commit is contained in:
seahi 2024-12-01 22:36:24 +08:00
parent 5a4df5e6f3
commit 4d9579e13d
3 changed files with 90 additions and 0 deletions

View File

@ -1,4 +1,27 @@
package chapter6;
import java.util.HashMap;
public class Example14 {
public static void main(String[] args) {
HashMap map = new HashMap(); // 创建Map对象
map.put("1","张三");//存储键和值
map.put("2","李四");
map.put("3","王五");
map.put("3", "赵六");
System.out.println("1" + map.get("1")); // 根据键获取值
System.out.println("2: " + map.get("2"));
System.out.println("3: " + map.get("3"));
System.out.println("键值对数量:" + map.size());
// if (map.containsKey("1")) {
// System.out.println("1号存在");
// }
//
// if (map.containsValue("李四")) {
// System.out.println("李四存在");
// }
}
}

View File

@ -1,4 +1,52 @@
package chapter6;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Example15 {
public static void main(String[] args) {
HashMap map = new HashMap(); // 创建Map对象
map.put("2","李四"); //存储键和值
map.put("3","王五");
map.put("1","张三");
// 方法一
Set keySet = map.keySet(); //获取键的集合
Iterator it = keySet.iterator();//选代键的集合
while (it.hasNext()) {
Object key = it.next();
Object value = map.get(key); //获取每个键所对应的值
System.out.println(key + ":" + value);
}
Iterator it2 = map.keySet().iterator();
while (it2.hasNext()) {
Object key = it2.next();
System.out.println(key);
}
Iterator it3 = map.values().iterator();
while (it3.hasNext()) {
Object value = it3.next();
System.out.println(value);
}
// 方法二
Set entrySet = map.entrySet(); // 获取所有映射关系
Iterator it4 = entrySet.iterator(); // 获取Iterator对象
while (it4.hasNext()){
//获取集合中键值对映射关系
Map.Entry entry = (Map.Entry) (it4.next());
Object key = entry.getKey();//获取Entry中的键
Object value = entry.getValue();//获取Entry中的值
System.out.println(key + ":" + value);
}
for (Object obj : map.entrySet()) {
System.out.println(obj);
}
}
}

View File

@ -1,4 +1,23 @@
package chapter6;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class Example19 {
public static void main(String[] args) {
TreeMap map = new TreeMap(); // 创建Map集合
map.put(3, "李四"); // 存储键和值
map.put(2, "王五");
map.put(4, "赵六");
map.put(3, "张三");
Set keySet = map.keySet();
Iterator iterator = keySet.iterator();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = map.get(key);
System.out.println(key + ":" + value);
}
}
}