Adds an element to the WeightedCollection with the specified weight. If the element is already present in the WeightedCollection the weight is added to the existing element instead. Note that this is means WeightedCollection does not guarantee order of the collection. @param weight Weigh
(E element, int weight)
| 172 | * if the given weight is less than zero |
| 173 | */ |
| 174 | public final boolean add(E element, int weight) |
| 175 | { |
| 176 | if (weight < 0) |
| 177 | { |
| 178 | throw new IllegalArgumentException("Cannot items with weight < 0"); |
| 179 | } |
| 180 | else if (weight == 0) |
| 181 | { |
| 182 | return false; |
| 183 | } |
| 184 | // Lets see if we can find this element |
| 185 | for (WeightedItem<E> item : theData) |
| 186 | { |
| 187 | E wiElement = item.getElement(); |
| 188 | if (Objects.equals(wiElement, element)) |
| 189 | { |
| 190 | item.addWeight(weight); |
| 191 | return true; |
| 192 | } |
| 193 | } |
| 194 | return theData.add(new WeightedItem<>(element, weight)); |
| 195 | } |
| 196 | |
| 197 | /** |
| 198 | * Adds the specified element with the default weight. |