Groovy String.contentEquals
Compare a String with the text in a CharSequence such as a StringBuilder.
A simple example
String.contentEquals
- Start with "ab" and a buffer holding ab
- Do this Compare the characters
- Result Equal
Syntax
public boolean contentEquals(StringBuffer sb)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyCompare a barcode buffer
A barcode reader builds a scan in a mutable buffer before the app receives it. Test whether its characters are already a complete match for the immutable barcode in the catalog.
def scan = new StringBuilder("BK").append(12)
println "BK12".contentEquals(scan)
true
The characters match even though the buffer has a different type.
Detect a partial scan
A scanner builds a label incrementally in a buffer before checking it against a stored code. Compare the completed characters and ensure that a partial scan cannot be accepted as the whole ticket.
println "AB17".contentEquals(new StringBuffer("AB1"))
false
The fourth character is missing.
Validate a locker ticket
The first reading comes from the ticket and the second from the lock. The reader compares both identifiers character for character. Do the two spellings match?
What to watch for
equals only accepts another String as an equal value. contentEquals can compare the contents of a mutable buffer.