John Walker
John Walker

Reputation: 291

Java UUID not being recognised after conversion to string

During the course of my programming I noticed the following behaviour. I would expect this code segment to print "They are equal" instead it prints "They are not equal", could anyone please explain this behaviour? Thank you.

public static void main(String[] args){
    UUID originalUUID = UUID.randomUUID();
    String string     = originalUUID.toString();
    UUID copiedUUID   = UUID.fromString(string);
    System.out.println("Original: " + originalUUID);
    System.out.println("Copy    : " + copiedUUID);
    if(originalUUID == copiedUUID){
        System.out.println("They are equal");
    }else{
        System.out.println("They are not equal");
    }
}

Upvotes: 0

Views: 148

Answers (2)

krishnang
krishnang

Reputation: 698

Just change your "==" to the following:

if(originalUUID.equals(copiedUUID)){
.
.

Upvotes: 0

Andy Thomas
Andy Thomas

Reputation: 86489

The == operator tests that the two references point to the same object -- not whether the two objects are equal.

If you want to test for object equality, use the equals() method, which is defined by the UUID class.

 if ( originalUUID.equals( copiedUUID )) {
    ...

Upvotes: 3

Related Questions