RangeSet extends AbstractSet<Long> implements Set<Long> { @Override public boolean add(Long aLong) { Map.Entry<Long, LongSegment> lowerEntry = map.floorEntry(aLong); if (lowerEntry != null && lowerEntry.getValue().contains(aLong)) { return false; } LongSegment upperSegment = map.get(aLong + 1); boolean lowerAdjacent = lowerEntry != null && lowerEntry.getValue().getMax() + 1 == aLong; boolean upperAdjacent = upperSegment != null && upperSegment.getMin() - 1 == aLong; if (lowerAdjacent && upperAdjacent) { map.put( lowerEntry.getValue().getMin(), new LongSegment(lowerEntry.getValue().getMin(), upperSegment.getMax())); map.remove(upperSegment.getMin()); } else if (lowerAdjacent) { map.put( lowerEntry.getValue().getMin(), new LongSegment(lowerEntry.getValue().getMin(), aLong)); } else if (upperAdjacent) { map.put(aLong, new LongSegment(aLong, upperSegment.getMax())); map.remove(upperSegment.getMin()); } else { map.put(aLong, new LongSegment(aLong)); } size++; return true; }  @Override int size(); @Override boolean contains(Object o); @Override Iterator<Long> iterator(); @Override boolean add(Long aLong); @Override boolean remove(Object o); @Override boolean removeAll(Collection<?> c); @Override void clear();  }
@Test(groups = "fast") public void testAdd() throws Exception { Assert.assertTrue(set.isEmpty()); Assert.assertEquals(set.size(), 0); Assert.assertTrue(set.add(0L)); Assert.assertTrue(set.contains(0L)); Assert.assertEquals(set.size(), 1); Assert.assertFalse(set.add(0L)); Assert.assertEquals(set.size(), 1); Assert.assertTrue(set.add(1L)); Assert.assertTrue(set.contains(1L)); Assert.assertEquals(set.size(), 2); Assert.assertFalse(set.add(1L)); Assert.assertEquals(set.size(), 2); Assert.assertTrue(set.add(-1L)); Assert.assertTrue(set.contains(-1L)); Assert.assertEquals(set.size(), 3); Assert.assertTrue(set.add(3L)); Assert.assertTrue(set.contains(3L)); Assert.assertEquals(set.size(), 4); Assert.assertTrue(set.add(-3L)); Assert.assertTrue(set.contains(-3L)); Assert.assertEquals(set.size(), 5); Assert.assertTrue(set.add(2L)); Assert.assertTrue(set.contains(2L)); Assert.assertEquals(set.size(), 6); Assert.assertFalse(set.add(2L)); Assert.assertEquals(set.size(), 6); }