KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mchange > v1 > util > SetUtils


1 /*
2  * Distributed as part of debuggen v.0.1.0
3  *
4  * Copyright (C) 2005 Machinery For Change, Inc.
5  *
6  * Author: Steve Waldman <swaldman@mchange.com>
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License version 2.1, as
10  * published by the Free Software Foundation.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this software; see the file LICENSE. If not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */

22
23
24 package com.mchange.v1.util;
25
26 import java.util.Iterator JavaDoc;
27 import java.util.Set JavaDoc;
28 import java.util.AbstractSet JavaDoc;
29 import java.util.HashSet JavaDoc;
30
31 public final class SetUtils
32 {
33     public static Set JavaDoc oneElementUnmodifiableSet(final Object JavaDoc elem)
34     {
35     return new AbstractSet JavaDoc()
36         {
37         public Iterator JavaDoc iterator()
38         { return IteratorUtils.oneElementUnmodifiableIterator( elem ); }
39
40         public int size() { return 1; }
41
42         public boolean isEmpty()
43         { return false; }
44
45         public boolean contains(Object JavaDoc o)
46         { return o == elem; }
47
48         };
49     }
50
51     public static Set JavaDoc setFromArray(Object JavaDoc[] array)
52     {
53     HashSet JavaDoc out = new HashSet JavaDoc();
54     for (int i = 0, len = array.length; i < len; ++i)
55         out.add( array[i] );
56     return out;
57     }
58
59     public static boolean equivalentDisregardingSort(Set JavaDoc a, Set JavaDoc b)
60     {
61     return
62         a.containsAll( b ) &&
63         b.containsAll( a );
64     }
65
66     /**
67      * finds a hash value which takes into account
68      * the value of all elements, such that two sets
69      * for which equivalentDisregardingSort(a, b) returns
70      * true will hashContentsDisregardingSort() to the same value
71      */

72     public static int hashContentsDisregardingSort(Set JavaDoc s)
73     {
74     int out = 0;
75     for (Iterator JavaDoc ii = s.iterator(); ii.hasNext(); )
76         {
77         Object JavaDoc o = ii.next();
78         if (o != null) out ^= o.hashCode();
79         }
80     return out;
81     }
82 }
83
84
Popular Tags