chinabugotech/hutool · error · UnsupportedOperationException

ComparatorChains must contain at least one Comparator

Error message

ComparatorChains must contain at least one Comparator

What it means

Thrown by ComparatorChain.compare() on the first invocation if the chain contains zero comparators. The no-arg constructor creates an empty chain, and checkChainIntegrity() is called before the first comparison to ensure at least one comparator exists. A ComparatorChain with no comparators cannot produce a meaningful comparison.

Source

Thrown at hutool-core/src/main/java/cn/hutool/core/comparator/ComparatorChain.java:352

	/**
	 * 被锁定时抛出异常
	 *
	 * @throws UnsupportedOperationException 被锁定抛出此异常
	 */
	private void checkLocked() {
		if (lock == true) {
			throw new UnsupportedOperationException("Comparator ordering cannot be changed after the first comparison is performed");
		}
	}

	/**
	 * 检查比较器链是否为空,为空抛出异常
	 *
	 * @throws UnsupportedOperationException 为空抛出此异常
	 */
	private void checkChainIntegrity() {
		if (chain.size() == 0) {
			throw new UnsupportedOperationException("ComparatorChains must contain at least one Comparator");
		}
	}
	//------------------------------------------------------------------------------------------------------------------------------- Private method start
}

View on GitHub (pinned to 8870454b2a)

Solutions

  1. Always add at least one comparator before using the chain: chain.addComparator(...) or use a parameterized constructor.
  2. Use the static factory ComparatorChain.of(comparator) which requires at least one comparator.
  3. Check chain.size() > 0 before passing the chain to a sort or comparison operation.

Example fix

// before
ComparatorChain<MyType> chain = new ComparatorChain<>();
// forgot to add comparators
list.sort(chain); // throws on first compare

// after
ComparatorChain<MyType> chain = ComparatorChain.of(
    Comparator.comparing(MyType::getName)
);
list.sort(chain);
Defensive patterns

Strategy: validation

Validate before calling

if (chain.size() == 0) {
    throw new IllegalStateException("ComparatorChain must have at least one comparator before use");
}

Prevention

When it happens

Trigger: Constructing a ComparatorChain with the no-arg constructor (new ComparatorChain()) and then using it in a sort or comparison without adding any comparators via addComparator(). The error surfaces on the first compare() call, not at construction time.

Common situations: Creating an empty ComparatorChain and forgetting to add comparators before use. Dynamically building a chain where the comparator-adding logic produces zero entries due to a filtering bug. Using a ComparatorChain as a field that was initialized but never populated.

Related errors


AI-assisted analysis of chinabugotech/hutool@8870454b2a (2026-08-14). Data as JSON: /api/errors/03d0a88b5e183784. Report an issue: GitHub.