Skip to content

Instantly share code, notes, and snippets.

@Malex
Created July 10, 2018 08:57
Show Gist options
  • Save Malex/87a63494138c11acdbbd038e32c2ee94 to your computer and use it in GitHub Desktop.
Save Malex/87a63494138c11acdbbd038e32c2ee94 to your computer and use it in GitHub Desktop.
Method TrimBook and its test
/*
This was a method used to resize the array of books in library before switching to collections. Saving here in case in the future a need
to resize array in languages without dynamic collections
*/
/*Method to resize array after removing elements*/
void trimBooks() {
int count = 0,shift=0;
for (int i=0; i < this.books.length; i++) {
if(this.books[i]==null) { //Finding how many elements were removed, saving in count
count++;
}
}
Book[] new_book = new Book[this.books.length-count];
for (int i=0; i < this.books.length-count;i++) { // Filling new array
while(this.books[i+shift]==null) { //Counting number of blanks from location in cycle
shift++;
}
new_book[i]=this.books[i+shift];
}
this.books = new_book;
}
// The test for the above method in Library
@Test
public void testTrimBooks() {
Book[] b = new Book[4];
b[0]=new Book(1,"Sanremo",new Author(3,"Pippo","Baudo"));
b[1]=new Book(4,"Sawnremo",new Author(3,"Pippo","Baudo"));
b[2]=null;
b[3]=new Book(5,"Sanremeeeo",new Author(5,"Pippow","Baudow"));
Library lib = new Library();
lib.addBooks(b);
lib.trimBooks();
b = new Book[3];
b[0]=new Book(1,"Sanremo",new Author(3,"Pippo","Baudo"));
b[1]=new Book(4,"Sawnremo",new Author(3,"Pippo","Baudo"));
b[2]=new Book(5,"Sanremeeeo",new Author(5,"Pippow","Baudow"));
assertTrue(Arrays.equals(b, lib.getBooks()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment