Results 1 to 3 of 3
  1. #1
    counterfox is offline Member
    Join Date
    Mar 2009
    Posts
    45
    Rep Power
    0

    Default How to find out if part of an array is empty

    Say we have a simple array like this:

    class test{

    public static void main(String[] args){
    int arr[] = new int[10];
    for(int i=0;i<4;i++){
    arr[i] = i;
    }
    for(int j=0;j<arr.length;j++){
    System.out.println(arr[j]);
    }
    }
    }


    where the array has only a few parts of it given values. Is there any way to know in a sort of test what parts of the array are empty.

    Because when I run this is cmd, i get 0 in each of the empty parts but I'm thinking also from that program position 0 also contains "0" as was done in the for loop.

    thanks in advance

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,007
    Blog Entries
    7
    Rep Power
    20

    Default

    An array never contains 'empty' elements because when you create one all bits of all elements are set to zero. For an array of primitives this means that all elements contain a form of 0, 0L, 0.0 etc. For an array of objects all elements contain null.

    You have to find a 'sentinel' value, i.e. a value that you normally don't use and indicates an 'empty' value. Of course the value isn't really empty but it denotes an unused element. Also, have a look at the ArrayList class, it only stores elements you have actually stored in there.

    kind regards,

    Jos
    Last edited by JosAH; 10-13-2010 at 06:21 PM.

  3. #3
    rohitjava is offline Member
    Join Date
    Aug 2010
    Posts
    13
    Rep Power
    0

Similar Threads

  1. find the unique values of a double array
    By tyang in forum New To Java
    Replies: 3
    Last Post: 09-11-2011, 02:47 PM
  2. Find max number in 2D array?
    By spatel14 in forum New To Java
    Replies: 3
    Last Post: 06-30-2010, 04:27 PM
  3. Replies: 1
    Last Post: 04-15-2010, 05:40 PM
  4. How do I count empty spaces in a byte array?
    By nessa203 in forum New To Java
    Replies: 13
    Last Post: 01-11-2010, 05:46 PM
  5. FInd the no. of duplicates in an array
    By singularity in forum Advanced Java
    Replies: 3
    Last Post: 09-04-2009, 09:25 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •