Dani
Dani

Reputation: 71

Resizing arrayArray

I am trying to create a Boolean method to resize my array and return true if widening or false for narrowing! here is what I have done so far, please help me i don't know what tod od for the rest:)

public class StringArray implements InterfaceStringArray{

String[] strArray; // create an array & store value
private int nElems =0;  // number of elements
final int ARRAY_MAX = 100;



    StringArray bubbleSort= new StringArray();     // create bubbleSort object
    StringArray selectSort = new StringArray();    // create selectSort object
    StringArray insertSort = new StringArray();   // create insertSort object


public void initialize (int arrSize) { //initializes an array of size=arrSize
    strArray = new String [arrSize]; 
}


public int getSize() { //returns the current array size
    return strArray.length;
}




public boolean resize(int newSize) { //returns true if successful (widening), false if narrowing
    String[] newArray = new String[ strArray.length * 2];

    for ( int x=0; x < strArray.length; x++){ // Load array
        if (newArray[x].equals(strArray[x]) )
        return true;
    }
    return false;
}

Upvotes: 0

Views: 488

Answers (1)

petajamaja
petajamaja

Reputation: 530

OK , even though using ArrayList < String > would be better for your task, I'll just try to stick to your current implementation and re-write the resize() method.

/*
 *  A method to resize the array.
 *  @param  : newSize - new required size of array
 *  @return : true if widening, false if narrowing
 *
 */
public boolean resize(int newSize) { 

    boolean toReturn = true;

    // if narrowing or the size isn't being changed, return value changes to false; 
    if ( newSize <= strArray.length ){
         toReturn = false;
    }

    String[] newArray = new String[newSize];

    // yes, Java allows creating zero-sized arrays

    if(newSize != 0){

       // copying from old array to new one; it doesn't matter if this is narrowing 
       // or widening, everything that fits in will be copied
       System.arraycopy(strArray,0,newArray,0,newSize);

       // copying pointer to newArray to the variable where strArray used to be
       strArray = newArray;

    }
    return(toReturn);

}

What your current implementation does is absolutely different from your goal. First, you are doubling your array size instead of setting it with parameter newSize. Secondly, your method proceeds like this :

  • create a double sized array;
  • iterate through the main array and in each step compare String in strArray with String in newArray;
  • as soon as the Strings on position x are equal, return true;
  • if none are equal, return false;

Note: it will always return false, because newArray is empty.

Some reading about ArrayLists:

Unfortunately the best books about Java that I know are written in Czech, so I can't advise anything unless you speak that language...

Upvotes: 2

Related Questions