René's URL Explorer Experiment


Title: Comparable and Comparator in Java: Java TreeSet Drops

Open Graph Title: Comparable and Comparator in Java: Java TreeSet Drops

Description: TreeSet uses compareTo for equality, not equals(). Two objects returning 0 means one gets dropped silently. Avoid this data loss bug in sorted collections.

Open Graph Description: TreeSet uses compareTo for equality, not equals(). Two objects returning 0 means one gets dropped silently. Avoid this data loss bug in sorted collections.

Opengraph URL: https://thecodeforge.io/java/comparable-comparator-java/

direct link

Domain: thecodeforge.io


Hey, it has json ld scripts:
{
  "@context": "https://schema.org",
  "@type": "TechArticle",
  "mainEntityOfPage": {
    "@type": "WebPage",
    "@id": "https://thecodeforge.io/java/comparable-comparator-java/"
  },
  "headline": "Java TreeSet Drops Objects — compareTo Equality Trap",
  "description": "TreeSet uses compareTo for equality, not equals(). Two objects returning 0 means one gets dropped silently. Avoid this data loss bug in sorted collections.",
  "keywords": "Java TreeSet Drops Objects — compareTo Equality Trap, Java, Intermediate, Collections, TreeSet uses compareTo for equality, not equals(). Two objects returning 0 means one gets dropped silently. Avoid this data loss bug in sorted collections.",
  "proficiencyLevel": "Intermediate",
  "author": {
    "@type": "Person",
    "@id": "https://thecodeforge.io/about/#naren",
    "name": "Naren",
    "url": "https://thecodeforge.io/about/"
  },
  "publisher": {
    "@type": "Organization",
    "@id": "https://thecodeforge.io/#org",
    "name": "TheCodeForge",
    "url": "https://thecodeforge.io",
    "logo": {"@type": "ImageObject", "url": "https://thecodeforge.io/assets/og-image.png"}
  },
  "datePublished": "2026-03-05T00:00:00+00:00",
  "dateModified": "2026-08-30T00:00:00+00:00",
  "url": "https://thecodeforge.io/java/comparable-comparator-java/",
  "inLanguage": "en",
  "educationalLevel": "Intermediate",
  "image": "https://thecodeforge.io/assets/og-image.png",
  "isPartOf": {"@id": "https://thecodeforge.io/#website"}
}
{
  "@context": "https://schema.org",
  "@type": "BreadcrumbList",
  "itemListElement": [
    {"@type": "ListItem", "position": 1, "name": "Home", "item": "https://thecodeforge.io/"},
    {"@type": "ListItem", "position": 2, "name": "Java", "item": "https://thecodeforge.io/java/"},
    {"@type": "ListItem", "position": 3, "name": "Java TreeSet Drops Objects — compareTo Equality Trap", "item": "https://thecodeforge.io/java/comparable-comparator-java/"}
  ]
}
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Can I use both Comparable and Comparator for the same class?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes, you can. Comparable defines the natural ordering, and Comparators provide alternative views. They are not mutually exclusive. In fact, it's a common pattern to implement Comparable for the default sort and expose named Comparator constants for specific use cases."
      }
    },
    {
      "@type": "Question",
      "name": "What happens if I pass a Comparator to TreeSet but the class also implements Comparable?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "The Comparator takes precedence. TreeSet will use the provided Comparator for all ordering and equality checks and ignore the natural ordering from Comparable. This allows you to override the default ordering for a particular sorted collection."
      }
    },
    {
      "@type": "Question",
      "name": "Why does my TreeSet allow duplicate elements?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "TreeSet does not allow duplicates according to compareTo. If you see duplicates, it means your compareTo method returns non-zero for objects that you consider duplicates. Check that compareTo returns 0 when you want objects to be considered equal. Alternatively, ensure consistency between compareTo and equals."
      }
    },
    {
      "@type": "Question",
      "name": "How do I sort by a field that can be null?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Use Comparator.nullsFirst() or nullsLast() to define where nulls should appear in the sorted order. For example: `Comparator.nullsLast(Comparator.comparing(Employee::getSalary))` places employees with null salary at the end of the sorted list."
      }
    },
    {
      "@type": "Question",
      "name": "Why is it important to have a stable sort for multi-field comparisons?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "A stable sort preserves the relative order of elements with equal sort keys. Java's Collections.sort() and Arrays.sort() use a stable sort (TimSort). However, TreeSet is not stable because it uses a tree structure. For multi-field comparisons, if the first field is equal, the second field determines order, so stability is less of a concern. But if you rely on insertion order as a tie-breaker, a stable sort is important."
      }
    }
  ]
}

og:typewebsite
og:imagehttps://thecodeforge.io/assets/og-image.png
og:image:width1200
og:image:height630

Links:

TheCodeForge https://thecodeforge.io/
Javahttps://thecodeforge.io/java/
Buy me a coffee https://ko-fi.com/thecodeforge
1Collections Framework Overviewhttps://thecodeforge.io/java/collections-framework-java/
2ArrayList in Javahttps://thecodeforge.io/java/arraylist-java/
3LinkedList in Javahttps://thecodeforge.io/java/linkedlist-java/
4HashMap in Javahttps://thecodeforge.io/java/hashmap-java/
5HashSet in Javahttps://thecodeforge.io/java/hashset-java/
6TreeMap and TreeSet in Javahttps://thecodeforge.io/java/treemap-treeset-java/
7Stack and Queue in Javahttps://thecodeforge.io/java/stack-queue-java/
8Iterator and ListIterator in Javahttps://thecodeforge.io/java/iterator-listiterator-java/
9LinkedHashMap and LinkedHashSethttps://thecodeforge.io/java/linkedhashmap-linkedhashset-java/
10PriorityQueue in Javahttps://thecodeforge.io/java/priorityqueue-java/
11Comparable and Comparator in Javahttps://thecodeforge.io/java/comparable-comparator-java/
12Collections Utility Class in Javahttps://thecodeforge.io/java/collections-utility-class-java/
13Deque and ArrayDeque in Javahttps://thecodeforge.io/java/deque-arraydeque-java/
14ConcurrentHashMap in Javahttps://thecodeforge.io/java/concurrenthashmap-java/
15EnumMap and EnumSet in Javahttps://thecodeforge.io/java/enummap-enumset-java/
16WeakHashMap in Javahttps://thecodeforge.io/java/weakhashmap-java/
17IdentityHashMap in Javahttps://thecodeforge.io/java/identityhashmap-java/
18Java flatMap(): Flatten Streams and Optionalhttps://thecodeforge.io/java/java-flatmap/
19HashMap vs Hashtable in Javahttps://thecodeforge.io/java/java-hashmap-vs-hashtable/
20Java Stream filter(): Filter Collections with Lambdashttps://thecodeforge.io/java/java-stream-filter/
21Java Map containsKey(): Check if a Key Existshttps://thecodeforge.io/java/java-map-containskey/
← Back to Java track https://thecodeforge.io/java/
Homehttps://thecodeforge.io/
Javahttps://thecodeforge.io/java/
Follow https://www.linkedin.com/in/thecodeforge-io-a0676b3b5/
 ● Production Incidenthttps://thecodeforge.io/java/comparable-comparator-java/#v2-production-incident
 🔎 Debug Guidehttps://thecodeforge.io/java/comparable-comparator-java/#v2-debug-guide
 ⚙ Triage Commandshttps://thecodeforge.io/java/comparable-comparator-java/#v2-triage-commands
designhttps://thecodeforge.io/java/design-patterns-java/
Stringshttps://thecodeforge.io/java/strings-java/
Red-Black treehttps://thecodeforge.io/dsa/red-black-tree/
HashSethttps://thecodeforge.io/java/hashset-java/
recordshttps://thecodeforge.io/java/records-java16/
constructorshttps://thecodeforge.io/java/constructors-java/
Java 8https://thecodeforge.io/interview/java8-interview-questions/
factoryhttps://thecodeforge.io/java/factory-pattern-java/
workinghttps://thecodeforge.io/java/json-java/
method referenceshttps://thecodeforge.io/java/method-references-java/
memoisationhttps://thecodeforge.io/javascript/memoisation-javascript/
ArrayListhttps://thecodeforge.io/java/arraylist-java/
→Java TreeSet Comparator — How It Silently Drops DuplicatesTreeSet comparator defined only on score caused 950 leaderboard entries to be silently dropped. Add a tiebreaker comparahttps://thecodeforge.io/java/treemap-treeset-java/
→Java binarySearch — Silent Failures on Unsorted ListsbinarySearch returns arbitrary indices on unsorted lists without throwing exceptions. Production searches fail silentlyhttps://thecodeforge.io/java/collections-utility-class-java/
→Binary Search Tree — Why Sorted Inserts Kill O(log n)100K sorted inserts turned BST search from 1ms to 30s — height became 100K instead of 17. See the fix production systemshttps://thecodeforge.io/dsa/binary-search-tree/
→Java PriorityQueue — Mutating Fields Breaks Heap OrderPriorityQueue does not re-heapify after object field changes; low-priority tasks run before high-priority. Remove and rehttps://thecodeforge.io/java/priorityqueue-java/
→Array Sorting in Java — Appended Items Break Binary SearchArrays.sort() runs once, not continuously. New items appended after sorting caused binary search failures and price-jumphttps://thecodeforge.io/java/array-sorting-java/
Caesar Cipher — Substitution EncryptionBeginnerhttps://thecodeforge.io/dsa/caesar-cipher/
Follow https://www.linkedin.com/in/thecodeforge-io-a0676b3b5/
←PreviousPriorityQueue in Javahttps://thecodeforge.io/java/priorityqueue-java/
NextCollections Utility Class in Java→https://thecodeforge.io/java/collections-utility-class-java/
LinkedIn https://www.linkedin.com/in/thecodeforge-io-a0676b3b5/
Facebook https://www.facebook.com/profile.php?id=61583020033815
YouTube https://www.youtube.com/channel/UCMar7CF2EmCF1I2tw1tNVuQ
Javahttps://thecodeforge.io/java/
Pythonhttps://thecodeforge.io/python/
C / C++https://thecodeforge.io/c-cpp/
JavaScripthttps://thecodeforge.io/javascript/
DSAhttps://thecodeforge.io/dsa/
Databasehttps://thecodeforge.io/database/
System Designhttps://thecodeforge.io/system-design/
DevOpshttps://thecodeforge.io/devops/
C# / .NEThttps://thecodeforge.io/csharp/
PHPhttps://thecodeforge.io/php/
ML / AIhttps://thecodeforge.io/ml-ai/
Interviewhttps://thecodeforge.io/interview/
CS Fundamentalshttps://thecodeforge.io/cs-fundamentals/
Rusthttps://thecodeforge.io/rust/
Toolshttps://thecodeforge.io/tools/
Cheatsheetshttps://thecodeforge.io/cheatsheets/
Mobilehttps://thecodeforge.io/mobile/
Data Analyticshttps://thecodeforge.io/data-analytics/
Securityhttps://thecodeforge.io/security/
Frontendhttps://thecodeforge.io/frontend/
Data Engineeringhttps://thecodeforge.io/data-engineering/
Testinghttps://thecodeforge.io/testing/
Cloudhttps://thecodeforge.io/cloud/
Observabilityhttps://thecodeforge.io/observability/
Web Platformhttps://thecodeforge.io/web-platform/
🧯 Errors Explainedhttps://thecodeforge.io/errors/
⚒ Blueprintshttps://thecodeforge.io/blueprints/
⌨ Practicehttps://thecodeforge.io/practice/
Interview Prephttps://thecodeforge.io/interview/
DSA Problemshttps://thecodeforge.io/dsa/
Developer Toolshttps://thecodeforge.io/tools/
Cheat Sheetshttps://thecodeforge.io/cheatsheets/
Abouthttps://thecodeforge.io/about/
Sitemaphttps://thecodeforge.io/sitemap.xml
Privacyhttps://thecodeforge.io/privacy.html

Viewport: width=device-width, initial-scale=1.0

Robots: max-image-preview:large


URLs of crawlers that visited me.