: : : : What would be the best way to count how often a number (or several
: : : : numbers) occurs in a java array ?
: : : :
: : : : Thanks.
: : :
: : :
: : : Try this one..... thanks!
: : :
: : : import java.util.*;
: : :
: : : // programmed in JDK 1.3
: : : public class FindOccurence {
: : : public static void main(String[] args) {
: : : System.out.println(
: : : find(new int[]{1,1,1,2,2,2,2,2,2,3,3,4,5,5,5,5}, 2)
: : : );
: : : }
: : :
: : : static int find(int[] arr, int numToFind) {
: : : int occurence=0;
: : : List l=new ArrayList();
: : : for (int i = 0; i < arr.length; i++) { l.add(new Integer(arr[i]));
: : : }
: : : if(l.contains(new Integer(numToFind))) {
: : : for(int i=0, size=l.size();i<size;i++)
: : : if(numToFind==((Integer)l.get(i)).intValue()) ++occurence;
: : : }
: : : return occurence;
: : : }
: : : }
: : :
: : Why not omit the creation of the ArrayList and use the array
: : directly (it's faster)?
: :
: :
: : public static int find(int[] arr, int numToFind) {
: : int occurence=0;
: : for (int i = 0; i < arr.length; i++) {
: : if (arr[i] == numToFind)
: : occurence++;
: : return occurence;
: : }
: : : :
:
:
: yeah you're right about that... i must have overlooked that... coz i
: seldom use arrays when i'm programming... i got used to using the
: collections framework... =) tHANKS by the way.....
:
: By the way this algorithm if used on very large array capacity...
: will throw java.lang.OutOfMemoryError even the one in my post.....
:
: try this...
:
:
: public static void main(String[] args) {
: int[] large = new int[100000000];
: Arrays.fill(large, 1);
: System.out.println(find(large,1));
: }
:
: /*static int find(int[] arr, int numToFind) {
: int occurence=0;
: List l=new ArrayList();
: for (int i = 0; i < arr.length; i++) { l.add(new Integer(arr[i]));
: }
: if(l.contains(new Integer(numToFind))) {
: for(int i=0, size=l.size();i<size;i++)
: if(numToFind==((Integer)l.get(i)).intValue()) ++occurence;
: }
: return occurence;
: }*/
:
: public static int find(int[] arr, int numToFind) {
: int occurence=0;
: for (int i = 0; i < arr.length; i++)
: if (arr[i] == numToFind)
: occurence++;
: return occurence;
: }
:
That's only logical. Each int is 4 byte large. All the elements together are almost 400 MB in size, which is a lot larger than the standard JVM memory space. If you need more space you can request it using one of the java.exe command line options.
Side-note: your code will require a lot more. When the internal array of the ArrayList is too small, a bigger one is created and then the original is copied. Also since each object is essentially a 32-bit pointer to some memory location, each element in the ArrayList uses at least 8 bytes. This together with the copy action will mean that you will need at least 16 bytes per element. With an array of 100,000,000 elements, your code needs at least about 2.4 GB of memory!