Java 8 – zoneddatetime is not equal to another zoneddatetime

I created two zoneddatetime objects, which I think should be the same:

public static void main(String[] args) {
    ZoneId zid = ZoneId.of("America/New_York");
    ZoneOffset offset = ZoneOffset.from(LocalDateTime.Now().atZone(zid));
    zoneddatetime zdt0 = zoneddatetime.of(2014,8,24,21,10,1,777000002,offset);
    zoneddatetime zdt1 = zoneddatetime.of(2014,zid);
    boolean equals = Objects.equals(zdt0,zdt1);
    System.out.println("equals: " + equals);
}

In the debugger, I see that in the first case, the member class of the zoneddatetime area is Java time. Zoneoffset, the second case is Java time. Zoneregion, which makes zoneddatetime objects unequal It's confusing... Any ideas?

Solution

You are checking for object equality with a value of false because these objects are not equal One is bound to zoneid and the other is bound to zoneoffset If you want to check whether they represent the same time, you can use the very intuitive naming method isequal

For example:

ZoneId zid = ZoneId.of("America/New_York");
ZoneOffset offset = ZoneOffset.from(LocalDateTime.Now().atZone(zid));
zoneddatetime zdt0 = zoneddatetime.of(2014,offset);
zoneddatetime zdt1 = zoneddatetime.of(2014,zid);
System.out.println("isEqual:" + zdt0.isEqual(zdt1));
System.out.println("equals: " + zdt0.equals(zdt1));

Print:

isEqual:true
equals: false

By the way, note that you do not need to use objects. Net for the two known objects Equals (a, b) is not empty You can call A. equals (b) directly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>