.length on arrays you have already defined


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 2 of 2

Thread: .length on arrays you have already defined

  1. #1
    Join Date
    Jan 2004
    Posts
    10

    .length on arrays you have already defined

    i have predetermined the size of a 2 dimensional array in one section of my code, when i use array[].length i get back the full length to which i declared it to, is i possible to count just the number of spaces in the array, which are full , with out going back and unpredeterminig the size of the array, because , that cause a null pointer exception.

    Thanks , hope you can help.


    code portion 1
    Destination [][] Deststotarray = new Destination[20][20];

    code portion 2
    System.out.println(destinationarray[1].length); // is 20
    System.out.println(destinationarray.length); // is 20

  2. #2
    Join Date
    Nov 2003
    Posts
    22
    When you do:

    Destination [][] Deststotarray = new Destination[20][20];

    You are actually acllocating the space for 20 pointers to arrays of Destinations which can hold 20 destinations effectivly, so .length with allways be the size of the array in memory, not the number of things in it.

    There are several solutions to this:

    Firstly you could make a method that you pass the array of Destinations into, and it goes through and counts now many non null items there are inside the array.

    However if you are going to want to do this alot you might be better off making a class which has the array as a private member and some accessor functions to the array and keeps a count of the number of items so that it allways knows how many items there are in the array eg:

    Code:
    public class DestinationArray
    {
        private Destination[] dArray = new Destination[20];
       private int nextLocation = 0;
    
       public void addDestination(Destination d)
       {
          dArray[nextLocation++] = d;
       }
       
        public int getLength()
       {
         return nextLocation; 
       }
    
    }
    edit: Obviously this example code needs a bit more work before it is production quality :-)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center