Hello,
I hope I'm on right dev list and I'm posting it as it supposed to be posted. There is a RFE: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6680235 "A DESCRIPTION OF THE REQUEST : Java Lists currently do not have a way of getting the count of a particular customer within a List. JUSTIFICATION : I ran into this issue when I had a list of objects in which it contained some duplicates, and I needed to know the number of occurrences of specific objects within the list. Basically i built a list of referenced objects from a list of objects and needed the result of how many times a specific referenced customer was in this built list, for later use. I needed something like... myList.elementCount(obj); where elementCount() returns int number of occurrences or -1 if it does not exist in the list, and obj is the assumed element in the list. I was able to continue by creating a custom iterator, but the above alternative would have been a quicker solution. Posted Date : 2008-03-26 12:31:26.0" I see we can do the following: 1) add a method to java.util.AbstractCollection: /** * Returns the amount of specified element in this collection. If the * collection contains more than <tt>Integer.MAX_VALUE</tt> occurrences of * specified element, returns <tt>Integer.MAX_VALUE</tt>. * * This implementation iterates over the elements in the collection, * checking each element in turn for equality with the specified element. * * @param o object to be counted for in this collection. * @return the amount of specified element in this collection. */ public int elementCount(Object o) { Iterator e = iterator(); int count = 0; if (o==null) { while (e.hasNext()) { if (e.next()==null) { if (count<Integer.MAX_VALUE) { count++; } else break; } } } else { while (e.hasNext()) { if ((o.equals(e.next())&&(count<Integer.MAX_VALUE))) { if (count<Integer.MAX_VALUE) { count++; } else break; } } } return count; } 2) add a method definition to interface java.util.Collection: /** * Returns the amount of specified element in this collection. If the * collection contains more than <tt>Integer.MAX_VALUE</tt> occurrences of * specified element, returns <tt>Integer.MAX_VALUE</tt>. * * This implementation iterates over the elements in the collection, * checking each element in turn for equality with the specified element. * * @param o object to be counted for in this collection. * @return the amount of specified element in this collection. */ public int elementCount(Object o); 3) The java.util.AbstractSet can be optimized: public int elementCount(Object o) { if (contains(o)) { return 1; } else return 0; } any inputs/thoughts? Thanks -- All of best, Leszek
