简体   繁体   中英

Can someone help me increase the length of an array?

Basically, I need to create a new array (newList) one element bigger than the old array (PredatorList). The only thing I'm meant to edit from the code below is the stuff within the increaseArray method. I am not allowed to edit the method name/signature. I have to perform a Junit test on it but I keep getting an error and I don't know why. My code so far:

public class Pack {
/**
* Predator list.   This contains the list of all Predators. 
* The list should never contain a null in the middle and should never have more than one 
* blank at the end (eg a null).
*/
private Predator[] PredatorList = new Predator[0];

/**
* Increase the array by one.  You will need to create a new array one element 
* bigger than the old array. 
* No External Classes Permitted to Be Used in This Method
* My Solution Length in Lines (note yours can be longer or shorter): 3
* 
*/
private void increaseArray() {
   int increment = 1;
   Predator[] newList = new Predator[PredatorList.length + increment];
   for (int i = 0; i < PredatorList.length; i++) {
         newList[i] = PredatorList[i];
         }
   }

}

I have a PackTest class that shows this but I don't really know how to read it.

public void testAddPredator2()  
{  
  Pack list = null;  
  //add normal Predator  
  list = buildTestSet();  
  //System.out.println("->"+list.getNumberOfPredators());  
  int before = list.getNumberOfPredators();  
  list.addPredator(new Predator("Pony",100,100,5));  
  int after = list.getNumberOfPredators();  
  //System.out.println("->"+list.getNumberOfPredators());  
  assertEquals(before+1,after);  
  countOfSuccesfulTests++;  
}  

Any help would be great. Cheers!

You create a new list but don't assign it to the field with the original list afterwards.

this.PredatorList = newList;

is missing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM