001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.tang.util; 020 021import java.util.Collection; 022import java.util.Comparator; 023import java.util.TreeSet; 024 025public class MonotonicSet<T> extends TreeSet<T> { 026 private static final long serialVersionUID = 1L; 027 028 public MonotonicSet() { 029 super(); 030 } 031 032 public MonotonicSet(final TreeSet<T> c) { 033 super(c.comparator()); 034 addAll(c); 035 } 036 037 public MonotonicSet(final Comparator<T> c) { 038 super(c); 039 } 040 041 @Override 042 public boolean add(final T e) { 043 if (super.contains(e)) { 044 throw new IllegalArgumentException("Attempt to re-add " + e 045 + " to MonotonicSet!"); 046 } 047 return super.add(e); 048 } 049 050 @Override 051 public void clear() { 052 throw new UnsupportedOperationException("Attempt to clear MonotonicSet!"); 053 } 054 055 @Override 056 public boolean remove(final Object o) { 057 throw new UnsupportedOperationException("Attempt to remove " + o 058 + " from MonotonicSet!"); 059 } 060 061 @Override 062 public boolean removeAll(final Collection<?> c) { 063 throw new UnsupportedOperationException( 064 "removeAll() doesn't make sense for MonotonicSet!"); 065 } 066 067 @Override 068 public boolean retainAll(final Collection<?> c) { 069 throw new UnsupportedOperationException( 070 "retainAll() doesn't make sense for MonotonicSet!"); 071 } 072 073 @Override 074 public boolean addAll(final Collection<? extends T> c) { 075 for (final T t : c) { 076 add(t); 077 } 078 return c.size() != 0; 079 } 080 081 public boolean addAllIgnoreDuplicates(final Collection<? extends T> c) { 082 boolean ret = false; 083 for (final T t : c) { 084 if (!contains(t)) { 085 add(t); 086 ret = true; 087 } 088 } 089 return ret; 090 } 091}