java TreeSet
import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; public class TestArchiveMetaTreeSet { public static void main(String[] args) { Comparator<ArchiveMeta> comparator = new Comparator<ArchiveMeta>() { @Override public int compare(ArchiveMeta o1, ArchiveMeta o2) { return Long.compare(o1.getOffset(), o2.getOffset()); } }; TreeSet<ArchiveMeta> set = new TreeSet<>(comparator); ArchiveMeta entry1 = new ArchiveMeta(5, 1); set.add(entry1); ArchiveMeta entry2 = new ArchiveMeta(1, 3); set.add(entry2); set.add(new ArchiveMeta(3, 7)); set.add(new ArchiveMeta(2, 4)); Iterator<ArchiveMeta> iter = set.iterator(); while (iter.hasNext()) { ArchiveMeta item = iter.next(); System.out.println("offset: " + item.getOffset() + " id: " + item.getArchiveId()); } // boolean res = set.remove(entry1); ArchiveMeta entry3 = new ArchiveMeta(10, 3); //因为定义了比较器,删除时只比较offset,不比较对象,所以这样也是成功的。 boolean res = set.remove(entry3); System.out.println("res : " + res); iter = set.iterator(); while (iter.hasNext()) { ArchiveMeta item = iter.next(); System.out.println("offset: " + item.getOffset() + " id: " + item.getArchiveId()); } // res = set.remove(entry2); ArchiveMeta entry4 = new ArchiveMeta(25, 1); res = set.remove(entry4); System.out.println("res : " + res); iter = set.iterator(); while (iter.hasNext()) { ArchiveMeta item = iter.next(); System.out.println("offset: " + item.getOffset() + " id: " + item.getArchiveId()); } } } public class ArchiveMeta { public long archiveId; public long offset; public long getArchiveId() { return archiveId; } public long getOffset() { return offset; } public ArchiveMeta(long archiveId, long offset) { this.archiveId = archiveId; this.offset = offset; } }