Sayalic
Sayalic

Reputation: 7650

How to compare two proto buffer message in Java?

In package com.google.protobuf I found a Message interface, it claims it will compare by content:

public interface Message extends MessageLite, MessageOrBuilder {
  // -----------------------------------------------------------------
  // Comparison and hashing

  /**
   * Compares the specified object with this message for equality.  Returns
   * <tt>true</tt> if the given object is a message of the same type (as
   * defined by {@code getDescriptorForType()}) and has identical values for
   * all of its fields.  Subclasses must implement this; inheriting
   * {@code Object.equals()} is incorrect.
   *
   * @param other object to be compared for equality with this message
   * @return <tt>true</tt> if the specified object is equal to this message
   */
  @Override
  boolean equals(Object other);

But I write test code:

public class Test {
  public static void main(String args[]) {
    UserMidMessage.UserMid.Builder aBuilder = UserMidMessage.UserMid.newBuilder();
    aBuilder.setQuery("aaa");
    aBuilder.setCateId("bbb");
    aBuilder.setType(UserMidMessage.Type.BROWSE);
    System.out.println(aBuilder.build() == aBuilder.build());        
  }
}

It gives false.

So, how to compare to proto buffer message?

Upvotes: 7

Views: 16553

Answers (2)

Jordi Castilla
Jordi Castilla

Reputation: 26961

== compares object references, it checks to see if the two operands point to the same object (not equivalent objects, the same object), so you can be sure that .build() makes a new object each time...

To use the code you posted you must compare with equals

System.out.println(aBuilder.build().equals(aBuilder.build()));        

Upvotes: 13

Misch
Misch

Reputation: 10840

In Java, you need to compare objects with the equals method, not with the == operator. The problem is that == compares if it is the same object, whereas the equals method compares if they are equal with the provided implementation by the developer of the class.

System.out.println(aBuilder.build().equals(aBuilder.build()));

For more details, there are tons of questions about this already (for example Java == vs equals() confusion.

Upvotes: 4

Related Questions