Issue
In this code, we have to add a method set() which will take two parameters, an (int) index, and an Integer value, which will set the array element at the specified index to the specified value and the array will grow if an attempt is made to set a value beyond the end of the array.
public class MyVector {
protected Integer[] internalArray;
public MyVector( int initialSize )
{
internalArray = new Integer[initialSize];
}
public void resize( int newSize )
{
if ( newSize != internalArray.length ) {
Integer[] newArray = new Integer[newSize];
for (int i=0; i < Math.min(newSize,internalArray.length); i++)
newArray[i] = internalArray[i];
internalArray = newArray;
}
}
public Integer get( int index )
{
if ( index < internalArray.length )
return internalArray[index];
return null;
}
public static void main(String[] args)
{
MyVector vec = new MyVector(5);
for ( int i = 0 ; i < 20 ; i++ )
vec.set(i, i*i );
for ( int i = 0 ; i < 20 ; i++ )
System.out.println( "Element" + i + "=" + vec.get(i) );
}
}
I'm confused about how to execute the set() method, can anyone help?
public int set(int a, int b){
a = b;
if (b>19){
resize(b);
}
return a;
}
Solution
Your vector class contains an internal array. There you have to modify the value at the given position. If the given position is outside of the array then you can use the resize method to enlarge the internal array:
public class MyVector {
protected Integer[] internalArray;
public MyVector( int initialSize )
{
internalArray = new Integer[initialSize];
}
public void resize( int newSize )
{
if ( newSize != internalArray.length ) {
Integer[] newArray = new Integer[newSize];
for (int i=0; i < Math.min(newSize, internalArray.length); i++)
newArray[i] = internalArray[i];
internalArray = newArray;
}
}
public Integer get( int index )
{
if ( index < internalArray.length )
return internalArray[index];
return null;
}
public void set( int index, int value )
{
if (index > internalArray.length -1) {
resize(index + 1);
}
internalArray[index] = value;
}
public static void main(String[] args)
{
MyVector vec = new MyVector(5);
for ( int i = 0 ; i < 20 ; i++ )
vec.set(i, i*i );
for ( int i = 0 ; i < 20 ; i++ )
System.out.println( "Element" + i + "=" + vec.get(i) );
}
}
$ java MyVector.java
Element0=0
Element1=1
Element2=4
Element3=9
Element4=16
...
Element17=289
Element18=324
Element19=361
Answered By - Franck
Answer Checked By - Mildred Charles (JavaFixing Admin)