java enum 枚举比较 == or equals ??

2020-04-08  本文已影响0人  小程序猿一枚

问题 枚举比较报错 NPE

public static enum MessageDirection {
    SEND(1),
    RECEIVE(2);
}

在使用枚举比较时,使用了equals来比较两个枚举值

if(data.getMessageDirection().equals(Message.MessageDirection.SEND))    {   
    ...
 }

结果空指针了

    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean xxx.MessageDirection.equals(java.lang.Object)' on a null object reference
        at xxx.bindView(ConversationFragments.java:66)
        at xxx.bindView(ConversationFragments.java:31)
        at xxx.getView(BaseAdapter.java:111)
        at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:230)
        at android.widget.AbsListView.obtainView(AbsListView.java:2428)

解决方案

1、还是使用 equals 来比较,但是需要调转顺序

      if (Message.MessageDirection.SEND.equals(data.getMessageDirection()))    {    
            ...
         }

2、直接使用 ==

  if (data.getMessageDirection() == Message.MessageDirection.SEND)    { 
    ...
 }

查看enum源码

 /**
         * Returns true if the specified object is equal to this
         * enum constant.
         *
         * @param other the object to be compared for equality with this object.
         * @return  true if the specified object is equal to this
         *          enum constant.
         */
        public final boolean equals(Object other) {
            return this==other;
        }

发现源码中直接使用 ==

建议

枚举比较还是直接使用 == 来比较,这样比较直观,也可以避免使用equals因调用者为null而报空指针异常

https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

上一篇下一篇

猜你喜欢

热点阅读