KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > umd > cs > findbugs > gui > Grouper


1 /*
2  * FindBugs - Find bugs in Java programs
3  * Copyright (C) 2003,2004 University of Maryland
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  */

19
20 /*
21  * Grouper.java
22  *
23  * Created on April 5, 2003, 3:46 PM
24  */

25
26 package edu.umd.cs.findbugs.gui;
27
28 import java.util.Collection JavaDoc;
29 import java.util.Comparator JavaDoc;
30 import java.util.Iterator JavaDoc;
31
32 /**
33  * Given a sorted Collection and a Comparator, produces groups of objects
34  * that compare as equal. If the Collection is not sorted, this
35  * class will not work correctly.
36  *
37  * @author David Hovemeyer
38  */

39 public class Grouper <ElementType> {
40
41     public interface Callback <ElementType2> {
42         public void startGroup(ElementType2 firstMember);
43
44         public void addToGroup(ElementType2 member);
45     }
46
47     private Callback<ElementType> callback;
48
49     /**
50      * Creates a new instance of Grouper.
51      *
52      * @param callback the callback which receives the groups and elements
53      */

54     public Grouper(Callback<ElementType> callback) {
55         this.callback = callback;
56     }
57
58     /**
59      * Group elements of given collection according to given
60      * compartor's test for equality. The groups are specified by
61      * calls to the Grouper's callback object.
62      *
63      * @param collection the collection
64      * @param comparator the comparator
65      */

66     public void group(Collection JavaDoc<ElementType> collection, Comparator JavaDoc<ElementType> comparator) {
67         Iterator JavaDoc<ElementType> i = collection.iterator();
68         ElementType last = null;
69         while (i.hasNext()) {
70             ElementType current = i.next();
71             if (last != null && comparator.compare(last, current) == 0) {
72                 // Same group as before
73
callback.addToGroup(current);
74             } else {
75                 // Start of a new group
76
callback.startGroup(current);
77             }
78
79             last = current;
80         }
81     }
82
83 }
84
Popular Tags