0

If I have

class example {
int x;
int data[] = new int[x]
}

If I wanted to create a new method that creates a new array whose size is one greater than data's length how would I proceed? I don't understand how I can create a new array when I don't know the initial length and adding one to that?

5
  • 4
    Why not use ArrayList? Commented Apr 21, 2015 at 4:55
  • 1
    But, in your example it would appear to be 0 or 1+data.length Commented Apr 21, 2015 at 4:55
  • Why are you posting a code that won't compile ? Commented Apr 21, 2015 at 4:58
  • What functionality you want to achieve which couldn't be achieved by List? Commented Apr 21, 2015 at 5:02
  • 1
    It's not functionality, but rather a learning process. This is an introductory class, so I guess the professor isn't introducing ArrayList yet. Commented Apr 21, 2015 at 5:03

3 Answers 3

2

For a learning process :

You can dynamically create a array.

class example {
    int size;
    int data[];

    public example(int size) {
        this.size = size;
        this.data = new int[size];
    }
}

But You can not change the size of array once it is declared.

You need to create new array of bigger size and then copy the content of old array into it. You can have a look at Arrays.copyOf method. You can have look at this SO Answer.

You can add below method in your example class.

public void increaseSizeOfArray(int incrementSize) {
    if (incrementSize > 0 && data != null && data.length > 0) {
        int copiedArray[] = Arrays.copyOf(data, data.length + incrementSize);
        data = copiedArray;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Really useful. +1 if I had more rep.
0

Use like this or better use ArrayList

 class example {
    int x;
    int data[] = new int[x]
    int newArr[]=new int[data.length+1]
    }

Comments

0

Instead of doing that, I would rather create a new array that is double the length of the array. It is costly to always make a new arrays.

You of course couldn't do your method until you did something with the array to add elements to it. Once it has some elements you could double it in size, that way you wouldn't have to make a new one for a while. If the new double sized array becomes only 1/3 full, cut the total size in half to free up memory space.

Obviously each of these operations could be costly since your array could be large.

Alternatively you could also use an ArrayList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.