hi,
how can I make the size of the array is equal to the number of elements in the array

Edited 3 Years Ago by sk8ergirl

You can't. An array size is fixed when it is created, and cannot be changed.
All you can do is to create a second array of the right size, copy all the entries into that one, point any reference variables to the new array, then allow the original array to be garbage collected.
Or use an ArrayList.

Hi, that's sort of a vague question. If you you have elements in the array then it already has a size. You can find the size of the array by using its length property. For instance:

int[] ary = new int[10];
int j=0;
    for (int i=0;i<ary.length;i++)
    {
        j++;
        ary[i]= j;
    }

I think sk8ergirl is referring to the problem where you have a (large) array that's not fully populated with actual data, so you want to "fit" the array to the number of elements that you have actually used.

Thanks JC, so would this be helpful:

public static void main(String[] args) {

    //Create an ArrayList of Integer type
    ArrayList<Integer> ary = new ArrayList<Integer>(10);
    //Add only 6 values to the array 
    ary.add(10);
    ary.add(20);
    ary.add(30);
    ary.add(40);
    ary.add(50);
    ary.add(60);
    //Create another ArrayList to hold only the values that are
    //in the previous array, and not the whole size of the array
    ArrayList<Integer> ary2 = new ArrayList<Integer>(ary.size());
    System.out.println(ary.size());
    //Load the ary values into the ary2 array.
    ary2.addAll(ary);
    System.out.println(ary2.size());
}

Edited 3 Years Ago by Stuugie

Sorry, I was just trying stuff that I thought may help. I can't see how this can be done without using an ArrayList but I'm not the greatest with working with Java.

Is this closer?

public static void main(String[] args) {

        int cnt = 0;
        Integer[] arry;
        arry = new Integer[]{2,4,6,7,null,null,null,null};
        for (int i = 0;i<arry.length;i++){
            if (arry[i]!=null){
                cnt++;
            }
        }
        Integer[] arry2 = new Integer[cnt];
        for (int i = 0;i<arry2.length;i++){
            arry2[i]=arry[i];
            System.out.println(arry2[i]);
        }
    }

LoL, I feel like I should be asking the same question as sk8tergirl.

no....it will just take more memory as you are string null in array.
Better go with arraylist and if you seriously want array as outout,then change aray to arrayList using toArray() method of List.MAke array of size of ArrayList.

@IIM I wanted to do it with arrayList , but I was asked to do it using array , arrayList is easier to use for this kind of problem

Now you know what needs to be done, you may want to look at the Arrays.copyOf method, which implements just what we were talking about.

This article has been dead for over six months. Start a new discussion instead.