java字典类_Java字典类

java字典类

Java Dictionary is an abstract class. It was the parent class for any key-value mapping objects, such as Hashtable. However, it got deprecated in favor of the Map interface introduced in Java 1.2, which later on streamlined the Collections Framework. Dictionary doesn’t allow null for key and value.

Java词典是一个抽象类 。 它是任何键值映射对象(例如Hashtable)的父类。 但是,不赞成使用Java 1.2中引入的Map接口,该接口后来简化了Collections Framework 。 字典不允许键和值为null。

Note: Dictionary class has been obsolete and you shouldn’t use it. I use dictionary a lot in Python and got curious if there is a Dictionary class in Java? That’s how I got to know about the Dictionary class. The information provided here is just to have some idea about it if you are curious, try to avoid using it in your application.

注意 :Dictionary类已经过时了,您不应使用它。 我在Python中经常使用字典,并且对Java中是否有Dictionary类感到好奇? 这就是我对Dictionary类的了解。 如果您感到好奇,这里提供的信息只是对它有所了解,请尝试避免在应用程序中使用它。

Java字典方法 (Java Dictionary Methods)

This class declares 7 methods, which the implementation classes had to implement.

此类声明7个方法,实现类必须实现。

  1. int size(): returns the size of the dictionary.

    int size() :返回字典的大小。
  2. boolean isEmpty(): returns true if there are no key-value mappings, else false.

    boolean isEmpty() :如果没有键值映射,则返回true,否则返回false。
  3. Enumeration<K> keys(): returns the enumeration of the keys in the dictionary.

    Enumeration <K> keys() :返回字典中键的枚举。
  4. Enumeration<K> elements(): returns the enumeration of the values in the dictionary.

    Enumeration <K> elements() :返回字典中值的枚举。
  5. V get(Object key): returns the value associated with the key, if the key doesn’t exist then returns null.

    V get(Object key) :返回与键关联的值,如果键不存在,则返回null。
  6. V put(K key, V value): adds the key-value pair to the dictionary. If any of the key-value is null, then throws NullPointerException. If the key already exists, then the value associated is returned and then the new value is updated. If it’s a new key, then null is returned.

    V put(K key,V value) :将键值对添加到字典中。 如果任何键值为null,则抛出NullPointerException 。 如果键已经存在,则返回关联的值,然后更新新值。 如果是新密钥,则返回null。
  7. V remove(Object key): removes the key-value pair from the dictionary. The value associated with the key is returned. If the key doesn’t exist in the dictionary, then do nothing and null is returned.

    V remove(Object key) :从字典中删除键/值对。 返回与键关联的值。 如果键在字典中不存在,则不执行任何操作,并返回null。

词典实现类 (Dictionary Implementation Classes)

The only direct implementation of Dictionary is the Hashtable class. The Properties class extends Hashtable, so that is also an implementation of the Dictionary.

Dictionary的唯一直接实现是Hashtable类。 Properties类扩展了Hashtable,因此它也是Dictionary的实现。

Java字典初始化 (Java Dictionary Initialization)


Dictionary<String, Integer> dict = new Hashtable<>();

Dictionary support Generics, so we can specify the key-value types while declaring and instantiating the Dictionary object.

Dictionary支持Generics ,因此我们可以在声明和实例化Dictionary对象时指定键值类型。

带值的字典初始化 (Dictionary Initialization with Values)

The Hashtable class has a constructor that accepts a Map and copy its key-pair to the Hashtable object. We can use it to initialize a dictionary with values.

Hashtable类具有一个构造函数 ,该构造函数接受Map并将其密钥对复制到Hashtable对象。 我们可以使用它来初始化带有值的字典。


Map<String, String> tempMap = new HashMap<>();
tempMap.put("1", "One");

Dictionary<String, String> dict1 = new Hashtable<>(tempMap);
		
System.out.println(dict1); // prints {1=One}

Java字典与地图 (Java Dictionary vs Map)

  • Dictionary is an abstract class whereas Map is an interface.

    字典是一个抽象类,而地图是一个接口
  • Dictionary class has been deprecated when Collection classes were streamlined and Map got introduced in JDK 1.2

    在精简Collection类和在JDK 1.2中引入Map后,不推荐使用Dictionary类。
  • Don’t use Dictionary in your applications, it’s better to use Map.

    不要在应用程序中使用Dictionary,最好使用Map。

Java字典vs哈希表 (Java Dictionary vs Hashtable)

  • Dictionary is an abstract class where as Hashtable is the implementation of Dictionary.

    Dictionary是一个抽象类,其中Hashtable是Dictionary的实现。
  • Dictionary class has been deprecated whereas Hashtable is still being used. In fact, Hashtable is part of Collections framework and implements Map interface.

    不推荐使用字典类,而仍在使用Hashtable。 实际上,Hashtable是Collections框架的一部分,并实现Map接口。

如何检查字典中是否存在键 (How to Check if a Key Exists in Dictionary)

Here is a simple program where we are iterating over the enumeration of keys to check if the key exists in the dictionary or not.

这是一个简单的程序,我们在其中遍历键的枚举,以检查键是否存在于字典中。


Dictionary<String, String> dict = new Hashtable<>();
dict.put("1", "One");
dict.put("2", "Two");
dict.put("3", "Three");

Enumeration<String> keys = dict.keys();

boolean found = false;
String lookupKey = "2";
while (keys.hasMoreElements()) {
	String key = keys.nextElement();
	if (lookupKey.contentEquals(key)) {
		found = true;
		System.out.println(lookupKey + " is present in the dictionary.");
		break;
	}
}
if (!found)
	System.out.println(lookupKey + " is not present in the dictionary.");

We can also use the get() method to check if the key exists or not. If key doesn’t exists, then null is returned. Also, null values are not allowed, so it’s safe to use the null check for this.

我们还可以使用get()方法检查密钥是否存在。 如果键不存在,则返回null。 另外,不允许使用null值,因此使用null检查是安全的。


String value = dict.get(lookupKey);

if(value != null)
	System.out.println(lookupKey + " is present in the dictionary.");
else
	System.out.println(lookupKey + " is not present in the dictionary.");

结论 (Conclusion)

Dictionary is an obsolete class, so you shouldn’t use it in your application. You might be tempted to use it if you are coming from Python background, but avoid it and use Map and their implementation classes.

字典是一个过时的类,因此您不应在应用程序中使用它。 如果您来自Python背景,则可能会想使用它,但请避免使用它,并使用Map及其实现类。

翻译自: https://www.journaldev.com/39818/java-dictionary-class

java字典类

好的,我可以为您解答关于Java自定义字典、自定义注解和反射注入字典值到实体的问题。 首先,自定义字典是一种将一些常量或者枚举型的值封装在一起的方式。可以让代码更加易读、易维护。比如,我们可以定义一个字典,用来存储一些常量值,如: ``` public class GenderDict { public static final Integer MALE = 1; public static final Integer FEMALE = 2; } ``` 接下来,我们可以使用自定义注解来标记需要注入字典值的实体的属性上。比如,我们可以定义一个注解,如: ``` @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Dictionary { String value(); } ``` 在该注解中,我们使用@Retention和@Target注解来指定注解的保留策略和作用范围。同时,我们还可以使用value属性来指定注解的值,即该属性需要注入的字典值的名称。 最后,我们可以使用反射机制,在运行时动态地将字典值注入到实体中。具体的实现方式如下: ``` public class DictionaryInjector { public static void injectDictionary(Object obj) throws IllegalAccessException { Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Dictionary.class)) { Dictionary dict = field.getAnnotation(Dictionary.class); String dictName = dict.value(); String dictValue = getDictValue(dictName); field.setAccessible(true); field.set(obj, dictValue); } } } private static String getDictValue(String dictName) { // 从字典中获取对应的字典值 // 这里可以使用反射或者其他方式来实现 return GenderDict.MALE.equals(dictName) ? "男" : "女"; } } ``` 在上述代码中,我们首先使用Class对象获取实体的所有属性,然后通过判断该属性是否被@Dictionary注解标记来确定是否需要注入字典值。如果需要注入,则从注解中获取字典值的名称,然后通过反射机制将字典值注入到实体的属性中。 最后,我们可以在代码中使用如下方式来注入字典值: ``` public class User { @Dictionary("gender") private String gender; // getters and setters } public class Main { public static void main(String[] args) throws IllegalAccessException { User user = new User(); DictionaryInjector.injectDictionary(user); System.out.println(user.getGender()); // 输出 "男" } } ``` 在上述代码中,我们首先定义了一个User,并在其中使用@Dictionary注解标记了gender属性。然后,在Main中,我们创建了一个User对象,并调用DictionaryInjector的injectDictionary方法来注入字典值。最后,我们通过调用User对象的getGender方法来获取注入后的字典值。 希望这能够帮助您解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值