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

34 篇文章 0 订阅
11 篇文章 0 订阅

问题

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值