Evan F
Evan F

Reputation: 61

Add a value to an array?

I've just created a new array that is one larger than my previous array and I want to copy the values in my first array into my new one. How do I add a new value to the last index of the new array?

This is what I've tried:

public void addTime(double newTime) {
    if (numOfTimes == times.length)
        increaseSize();
    times[numOfTimes] = newTime;
}

Upvotes: 0

Views: 187

Answers (7)

btiernay
btiernay

Reputation: 8129

Consider Arrays.copyOf if working with arrays is a constraint:

import java.util.Arrays;
...
private void increaseSize() {
   // Allocate new array with an extra trailing element with value 0.0d
   this.times = Arrays.copyOf( times, times.length + 1 );
}
...

Note that if you are doing this type array management often and in unpredictable ways, you may want to consider one of the Java Collection Framework classes such as ArrayList. One of the design goals of ArrayList is to administer size management, much like the JVM itself administers memory management.

I've developed an online executable example here.

Upvotes: 0

Debobroto Das
Debobroto Das

Reputation: 862

Why not you use System.arraycopy function.

increaseSIze()
{
   double [] temp = new double[times.lebgth+1];
   System.arrayCopy(times,0,temp,0,times.length);
   times=temp;
}

after that you have times array with 1 increased size.

Upvotes: 1

ttt
ttt

Reputation: 11

I would recommend trying to use an object such as java.util.List rather than raw arrays. Then you can just do: times.add(newTime) and it handles the sizing for you.

Upvotes: 1

George
George

Reputation: 497

why wouldn't you want a java.util.ArrayList for this requirement? Practically, there won't be a need managing its size. You just simply do this:

 List<Double> list = new ArrayList<Double>();
 list.add(newTime);

Upvotes: 0

Clayton Louden
Clayton Louden

Reputation: 1076

The last item of an array is always at myArray.length - 1. In your case the last element from the times array is times[times.length - 1]. Have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html for more information about arrays.

But more importantly: If you're trying to change the capacity of your array, you are most likely using the wrong data structure for the job. Have a look at Oracle's Introduction to Collections (and especially the ArrayList class if you need an array-like index to access elements).

Upvotes: 0

Chris Dargis
Chris Dargis

Reputation: 6043

Array indices go from 0..n-1.

array[array.length - 1] will address the value at the end of the array.

Upvotes: 0

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

To set a new value to the last index you can do

times[times.length - 1] = newTime;

Upvotes: 0

Related Questions