/* * Primitive Collections for Java. * Copyright (C) 2003 Søren Bak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import bak.pcj.set.IntSet; import bak.pcj.set.IntOpenHashSet; import bak.pcj.IntIterator; /** * This examplifies the operations of a set. * * @author Søren Bak * @version 1.0 2003/14/1 */ public class SetExample { public static void main(String[] args) { IntSet s = new IntOpenHashSet(); // Adding elements s.add(1); // s={1} s.add(2); // s={1,2} s.add(3); // s={1,2,3} s.add(4); // s={1,2,3,4} s.add(5); // s={1,2,3,4,5} s.add(2); // s={1,2,3,4,5} (not changed) s.add(4); // s={1,2,3,4,5} (not changed) // Removing elements s.remove(2); // s={1,3,4,5} s.remove(5); // s={1,3,4} // Clearing s.clear(); // s={} boolean c; c = s.isEmpty(); // c=true // Testing containment of elements s.add(1); s.add(2); s.add(3); // s={1,2,3} c = s.contains(1); // c=true, s={1,2,3} c = s.contains(3); // c=true, s={1,2,3} c = s.contains(5); // c=false, s={1,2,3} // Testing containment of collections IntSet t; t = new IntOpenHashSet(); t.add(1); // t={1}, s={1,2,3} c = s.containsAll(t); // c=true t.add(0); // t={0,1}, s={1,2,3} c = s.containsAll(t); // c=false // Adding collections s.addAll(t); // t={0,1}, s={0,1,2,3} // Retaining elements of collections t = new IntOpenHashSet(); t.add(2); t.add(3); t.add(4); t.add(5); // t={2,3,4,5}, s={0,1,2,3} s.retainAll(t); // t={2,3,4,5}, s={2,3} // Removing whole collections t = new IntOpenHashSet(); t.add(3); t.add(4); s.removeAll(t); // t={3,4}, s={2} // Finding the size int v; v = s.size(); // v=1, s={2} s.add(1); v = s.size(); // v=2, s={1,2} // Converting to an array int[] a = s.toArray(); // a=int[]{1,2}, s={1,2} // Iterating over elements for (int i = 0; i < 10; i++) s.add(i); // s={0,1,2,3,4,5,6,7,8,9} IntIterator i = s.iterator(); while (i.hasNext()) { int e = i.next(); if ((e % 2) == 1) i.remove(); } // s={0,2,4,6,8} // Comparing t = new IntOpenHashSet(s); // s={0,2,4,6,8}, t={0,2,4,6,8} c = s.equals(t); // c=true t.remove(2); // s={0,2,4,6,8}, t={0,4,6,8} c = s.equals(t); // c=false } }