在Java中,字典可以使用Java集合框架中的HashMap或TreeMap实现。下面是使用HashMap的示例:
import java.util.HashMap; import java.util.Map; public class DictionaryExample { public static void main(String[] args) { // 创建一个新的字典 Mapdictionary = new HashMap<>(); // 添加键值对到字典中 dictionary.put("apple", "苹果"); dictionary.put("banana", "香蕉"); dictionary.put("orange", "橙子"); // 获取字典中的值 String appleTranslation = dictionary.get("apple"); System.out.println("apple的翻译是:" + appleTranslation); // 检查字典中是否包含某个键 boolean containsBanana = dictionary.containsKey("banana"); System.out.println("字典中是否包含banana:" + containsBanana); // 删除字典中的键值对 dictionary.remove("orange"); // 迭代字典中的所有键值对 for (Map.Entry entry : dictionary.entrySet()) { String key = entry.getKey(); String value = https://www.yisu.com/ask/entry.getValue();"的翻译是:" + value); } } }
输出结果:
apple的翻译是:苹果 字典中是否包含banana:true apple的翻译是:苹果 banana的翻译是:香蕉