Home  >  Q&A  >  body text

java - 怎么判断map key对应的值是不是空的

System.out.println("a**"+map.get(a).getClass());
System.out.println("a**"+map.get(a));

-------------分割线------------
a**class java.util.ArrayList
a**[]

以上是控制台打印出来的东西。

map.get(a).toString().equals("");一直是false
map.get(a)!=null;一直是true

ringa_leeringa_lee2712 days ago2948

reply all(4)I'll reply

  • ringa_lee

    ringa_lee2017-04-18 09:09:32

    if(map.get(a)==null)Can’t you tell whether it is empty?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:09:32

    In Java, null and empty array are not the same concept. If you want to determine whether the array is empty, you can write it like this.

    `
    if (map.get(a) == null || map.get(a).size() == 0)
    `

    If it is a production environment, it is recommended to use tool classes, such as apache common或者spring都提供CollectionUtils.isEmpty(map.get(a))

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:09:32

    If an ArrayList has been instantiated, it is definitely not equal to null.
    Since the toString method can be executed without reporting an error, it must have been instantiated. Because toString is a method of the top-level parent class Object, how can an uninstantiated object have this method.

    ArrayList list = new ArrayList();
    System.out.println(list == null);  // false
    
    ArrayList list1 = null;
    System.out.println(list1.toString()); // 空指针

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:09:32

    map.get(a).toString().equals(""); is always false

    The result you print outa**[]可以看出来map.get(a).toString()不是空字符串,而是[],因此"[]".equals("")is always false

    map.get(a)! =null; always true

    If map.get(a).toString()没抛空指针异常,那么map.get(a) must be non-empty

    Judgment empty

    If the value corresponding to the key is always ArrayList, then you can use the following method:

    map.get(a) == null || map.get(a).isEmpty()

    reply
    0
  • Cancelreply