Library contents

Groovy String.contentEquals

Compare a String with the text in a CharSequence such as a StringBuilder.

A simple example

String.contentEquals

  1. Start with "ab" and a buffer holding ab
  2. Do this Compare the characters
  3. Result Equal
Both sequences hold a followed by b, even though the container types differ.

Syntax

Groovy 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.groovy

Compare 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.

Resulttrue
Lesson.groovy
def scan = new StringBuilder("BK").append(12)
println "BK12".contentEquals(scan)
Output
true

The characters match even though the buffer has a different type.

Advertisements

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.

Resultfalse
Lesson.groovy
println "AB17".contentEquals(new StringBuffer("AB1"))
Output
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?

Given'H07' · 'H07'
Worked resultMatch

What to watch for

equals only accepts another String as an equal value. contentEquals can compare the contents of a mutable buffer.

Documentation for String.contentEquals