diff --git a/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java b/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java index 552806e15bf0..b3512da95e5e 100644 --- a/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java +++ b/core/src/main/java/com/google/errorprone/bugpatterns/DoNotCallChecker.java @@ -143,6 +143,16 @@ public class DoNotCallChecker extends BugChecker .put( instanceMethod().onExactClass("java.sql.Time").named("toInstant"), "sqlTime.toInstant() is not supported. Did you mean to call toLocalTime() instead?") + .put( + instanceMethod() + .onDescendantOf("java.util.SortedMap") + .namedAnyOf("putFirst", "putLast"), + "Sorted collections do not support insertions with explicit positioning") + .put( + instanceMethod() + .onDescendantOf("java.util.SortedSet") + .namedAnyOf("addFirst", "addLast"), + "Sorted collections do not support insertions with explicit positioning") .put( instanceMethod() .onExactClass("java.util.concurrent.ThreadLocalRandom") diff --git a/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java b/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java index 2e9181bdd6dd..bc56b9d8ee26 100644 --- a/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java +++ b/core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java @@ -16,6 +16,7 @@ package com.google.errorprone.bugpatterns; +import static com.google.common.truth.TruthJUnit.assume; import static org.junit.Assert.assertThrows; import com.google.errorprone.CompilationTestHelper; @@ -516,6 +517,31 @@ public void badApis() { .doTest(); } + @Test + public void sortedCollectionSequencedCollectionMethods() { + assume().that(Runtime.version().feature()).isAtLeast(21); + testHelper + .addSourceLines( + "Test.java", + """ + import java.util.TreeMap; + import java.util.TreeSet; + public class Test { + public void foo(TreeMap map, TreeSet set) { + // BUG: Diagnostic contains: DoNotCall + map.putFirst("foo", "bar"); + // BUG: Diagnostic contains: DoNotCall + map.putLast("foo", "bar"); + // BUG: Diagnostic contains: DoNotCall + set.addFirst("foo"); + // BUG: Diagnostic contains: DoNotCall + set.addLast("foo"); + } + } + """) + .doTest(); + } + @Test public void readLock_newCondition() { assertThrows(