307 |
|
return al.iterator(); |
308 |
|
} |
309 |
|
|
310 |
+ |
/** |
311 |
+ |
* Compares the specified object with this set for equality. |
312 |
+ |
* Returns <tt>true</tt> if the specified object is also a set, |
313 |
+ |
* and every element of the specified set, as revealed by a single |
314 |
+ |
* traversal of its <tt>iterator()</tt>, is also contained in this |
315 |
+ |
* set at the point of call of this method, and no other elements |
316 |
+ |
* not present in the given set are contained in this set. |
317 |
+ |
* |
318 |
+ |
* @param o object to be compared for equality with this set |
319 |
+ |
* @return <tt>true</tt> if the specified object is equal to this set |
320 |
+ |
*/ |
321 |
+ |
public boolean equals(Object o) { |
322 |
+ |
if (o == this) |
323 |
+ |
return true; |
324 |
+ |
if (!(o instanceof Set)) |
325 |
+ |
return false; |
326 |
+ |
Set<?> set = (Set<?>)(o); |
327 |
+ |
Iterator<?> setIt = set.iterator(); |
328 |
+ |
|
329 |
+ |
// Uses O(n^2) algorithm that is only appropriate |
330 |
+ |
// for small sets, which CopyOnWriteArraySets should be. |
331 |
+ |
|
332 |
+ |
// Use a single snapshot of underlying array |
333 |
+ |
Object[] elements = al.getArray(); |
334 |
+ |
int len = elements.length; |
335 |
+ |
// Mark matched elements to avoid re-checking |
336 |
+ |
boolean[] matched = new boolean[len]; |
337 |
+ |
int k = 0; |
338 |
+ |
while (setIt.hasNext()) { |
339 |
+ |
if (++k > len) |
340 |
+ |
return false; |
341 |
+ |
Object x = setIt.next(); |
342 |
+ |
boolean found = false; |
343 |
+ |
for (int i = 0; i < len; ++i) { |
344 |
+ |
if (!matched[i] && eq(x, elements[i])) { |
345 |
+ |
matched[i] = true; |
346 |
+ |
found = true; |
347 |
+ |
break; |
348 |
+ |
} |
349 |
+ |
} |
350 |
+ |
if (!found) |
351 |
+ |
return false; |
352 |
+ |
} |
353 |
+ |
return k == len; |
354 |
+ |
} |
355 |
+ |
|
356 |
+ |
/** |
357 |
+ |
* Test for equality, coping with nulls. |
358 |
+ |
*/ |
359 |
+ |
private static boolean eq(Object o1, Object o2) { |
360 |
+ |
return (o1 == null ? o2 == null : o1.equals(o2)); |
361 |
+ |
} |
362 |
+ |
|
363 |
|
} |