How to compare two messages with a buffer in Java?

com.google.protobufI found the interface in the package Message, it claims that 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 am writing 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());        
  }
}

He gives false.

So, how to compare with the proto-buffer message?

+4
source share
2 answers

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

To use the code you submitted, you must compare with equals

System.out.println(aBuilder.build().equals(aBuilder.build()));        
+6
source

Java equals, ==. , == , , equals , .

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

(, Java == vs equals() .

+3

All Articles