Java: Dynamic Arrays

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Java: Associative Arrays

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:03 Dynamic Arrays
  • 0:46 Dynamic Arrays:…
  • 1:38 Creating a Class
  • 2:36 ArrayList
  • 4:05 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

Technically, Java doesn't support dynamic arrays. But in this lesson, we'll learn some alternative strategies for achieving a similar functionality and result.

Dynamic Arrays

You might think it would be pretty easy for an advanced language like Java to allow for a dynamic array, that is an array that can grow and shrink as needed. If I have an array with 5 elements and need to grow to 10, what's the harm in allowing this? It doesn't take much overhead for the system to generate those extra buckets in the array.

But what if the array is 2 and needs to grow to 20,000? Or what if we have an array of three dimensions and need to grow by ten-fold? All of a sudden there is a huge drain on system processing and memory usage to create the dynamic array. This is why Java doesn't natively support dynamic arrays. It's a memory hog and could really bog down the system. But we have ways of making this work.

Dynamic Arrays: Getting Started

You've made your array, and now you must live with it. Other programming languages might let you change the structure after it's made, but Java is a little stricter. For example, let's define the following array for the high scores of a game. We'll set the size to 10, as that seems reasonable.

Additionally, since Java is an object-oriented language, we will create a TopScores class that we use as games progress and are ended. This will also help us manipulate the array later!


class TopScores {
 void getScores() {
  //get and save scores here
 }
}
//Create our array to get top scores
TopScores[] topScores = new TopScores[10];


But, here's the thing. Now that we have the array set and the program's been running for some time, the boss stops by and wants the top 15 scores. Trashing the variable isn't feasible, so what do we do?

We could have declared the array to be 100 at the start, but it wouldn't make sense to build a huge array if we only wanted 10 or 15 buckets.

The following code makes use of the arraycopy feature in Java. It copies one array to another one.


//Create our array to get top scores
TopScores[] topScores = new TopScores[10];
//add a new high score, even if array is full
//we have to make a new array
int newSize = 15;
//make the new one 15
TopScores[] tempArray = new TopScores[15];
//new array
System.arraycopy(topScores, 0, tempArray, 0, newSize);
topScores = tempArray;


Creating a Class

This is a lot of work and can be hard to maintain if the array is going to be changing with any frequency. Instead, we can invest a little more time and coding to create our own class that lets us add or remove buckets in arrays.

We'll create a constructor inside our class. This is used to initialize an instance of our class. In this case, it's the DynamicArray object we create.


//create the array
private int[] topScores;
//we'll create an array that's 1 bucket
//this is called a constructor
public DynamicArray() {
 topScores = new int[1];
}
//let's pretend we have received another top score, so we'll set our position/bucket in the array to 2
int bucket = 2;
public int get(int bucket) {
 if(bucket >= topScores.length) {
  return 0;
 } else {
  return topScores[bucket];
 }
}
void put(int bucket, int value) {
 if(bucket >= topScores.length) {
  //we're already bigger than the array allows; increase the size
  int updatedSize = 2 * bucket;
  int[] newScores = new int[updatedSize];
  System.arraycopy(topScores, 0, newScores, 0, topScores.length);
  topScores = newScores;
  System.out.println("Array increased to " + updatedSize);
 }
topScores[bucket] = value;
}


As you can see, there is definitely a lot going on here, but the approach is similar to the first example. We're taking an array and replacing it with a bigger array should the need arise. The reason we've written a new class and methods is so we can use the put method anytime to bump up the size of the array.

So, when the boss stops by and wants another bucket for high scores, we can use a command to do so. First we can create an instance of the DynamicArray class, then we can run the put command to pass in the location and value. Remember that all Java arrays start counting at 0, so bucket 15 is really the 16th position!


//Boss wants another bucket
//Create instance of DynamicArray
DynamicArray reupdatedHighScores = new DynamicArray();
reupdatedHighScores.put(15, value);


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support