From 37101045af3595afdab0ca99abae643bb8d1fa95 Mon Sep 17 00:00:00 2001 From: asivache Date: Wed, 18 Mar 2009 21:44:30 +0000 Subject: [PATCH] a simple wrapper class; less overhead than keeping a separate Integer counter object and going through object reallocation and/or autoboxing on each counter increment git-svn-id: file:///humgen/gsa-scr1/gsa-engineering/svn_contents/trunk@90 348d0f76-0448-11de-a6fe-93d51630548a --- .../sting/indels/CountedObject.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100755 playground/java/src/org/broadinstitute/sting/indels/CountedObject.java diff --git a/playground/java/src/org/broadinstitute/sting/indels/CountedObject.java b/playground/java/src/org/broadinstitute/sting/indels/CountedObject.java new file mode 100755 index 000000000..234670d46 --- /dev/null +++ b/playground/java/src/org/broadinstitute/sting/indels/CountedObject.java @@ -0,0 +1,50 @@ +package org.broadinstitute.sting.indels; + +/** Utility class that makes working with counted objects slightly easier (and faster). + * Consider a "generic" counter representation as Map: updating the counter would require + * int i = map.get(obj).intValue(); i++; map.set(obj,i) - cumbersome, and also inefficient due to extra invocations of Integer + * constructor. This ObjectCounter class can increment its internally kept counter without the need to rebuild any objects, + * so one can use, e.g. "Set myset;" and then "myset.get(obj).increment()". Note that equals() method + * defines counted objects to be the same iff the underlying objects are equal, regardless of the + * counter value. Should the counters be compared, one has to use the getters on the two counted objects + * and compare the results. + * @author asivache + * + */ +public class CountedObject { + private T mObject; + int mCounter; + + /** Creates new counter associated with the passed object and assigns the default count of 1 + * + * @param o object to start counting for + */ + public CountedObject(T o) { + mObject = o; + mCounter = 1; + } + + /** Creates new counter associated with the object o and assigns specified initial count to it + * + * @param o object to start counting for + * @param n initial count + */ + public CountedObject(T o, int n) { + mObject = o; + mCounter = n; + } + + public T getObject() { return mObject; } + public int getCount() { return mCounter; } + public void increment() { mCounter++;} + public void increment(int n) { mCounter+=n; } + public void decrement() { mCounter--; } + public void decrement(int n) { mCounter -= n; } + @Override + public boolean equals(Object o) { + if ( this == o ) return true; + if ( ! ( o instanceof CountedObject )) return false; + return mObject.equals(o); + } + +}