Problem of the Day
Wednesday, January 22, 2025
Problem:
An int
Array such as the one shown here is initialized to a size of 10, which results in all of the elements being given an initial value of 0. A series of values are placed into the array, and an int
variable size
is used to identify both the current number of active values stored there, as well as the index of the next element in the array into which the next value will be placed.
Here, size = 5
, indicating both that there are 5 values stored in the array and that the next value to be stored in the array will be placed at position 5.
Consider the following class, which is intended to maintain such a collection of values in an int
Array.
public class IntArray
{
private int[] vals;
private int size;
/**
* Constructs a new IntArray with the capacity to store
* 10 values
*/
public IntArray()
{
// initialise instance variables
vals = new int[10];
size = 0; // indicates both the index where
// the next value will be placed and
// the "size" of the current number of values
}
/* methods not shown */
}
Which of the following methods will correctly add a value to the array and update the value of size
appropriately?
public void add(int value)
{
if (size < vals.length)
{
vals[size] = value;
size++;
}
}public void add(int value)
{
if (size < vals.length)
{
size++;
vals[size] = value;
}
}public void add(int value)
{
if (size < vals.length)
{
size++;
vals[0] = value;
}
}public void add(int value)
{
if (size < vals.length)
{
vals[0] = value;
size++;
}
}
The correct answer is a. When size
is initially set to 0
and a value is added, vals[size]
refers to vals[0]
, so the new value is placed at that position, index 0
. Then size
is incremented to 1
. That variable now refers to both the size of the "active" array (the elements of the array that have had values placed in them) as well as the index into which the next value will be placed (now 1
).