I am trying to create a method that returns an array that contains String representation of all MediaItem whose author matches the targetAuthor passed in. The array cannot contain any null values. If there are no matches the method returns an array of length 0. Here is my code
private ArrayList<MediaItem> itemList;
public MediaList(){
itemList = new ArrayList<MediaItem>();
}
...
public String[] getAllItemsByAuthor(String targetAuthor){
Object tempArray[] = itemList.toArray();
String targetAuthorArray[] = new String[tempArray.length];
for (int i = 0; i < tempArray.length; i++){
targetAuthorArray[i] = (String)tempArray[i];
}
int index = 0;
for (String value : targetAuthorArray){
if (Arrays.asList(targetAuthorArray).contains(targetAuthor)) {
targetAuthorArray[index] = String.valueOf(value);
}
}
return targetAuthorArray;
}
Here is the test that runs
@Test
public void getItemsByAuthorZeroMatchesTest() {
createListForTesting(mediaList);
String[] items = mediaList.getAllItemsByAuthor("No Author Matches This");
assertEquals("Test 36: Test the getAllItemsByAuthor method with zero matches.", 0, items.length);
}
When this test runs an error pops up
java.lang.ClassCastException: class Song cannot be cast to class java.lang.String (Song is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
I have another method thats supposed to do the same thing. It is supposed to return a new array that contains String representation of all MediaItems whose title matches the targetTitle passed in. It is supposed to use its toString() method and cannot return any null values
Here is my code
public String[] getAllItemsByTitle(String targetTitle){
String targetTitleArray[] = new String[itemList.size()];
int index = 0;
for (MediaItem value : itemList){
if (Arrays.asList(itemList).contains(targetTitle)) {
targetTitleArray[index] = String.valueOf(value);
}
}
return targetTitleArray;
}
I didn't use the toString method because I didn't know where to incorporate it but here is the code for it
public String toString(){
return title+", "+author+", "+genre;
}
When getAllItemsByTitle runs it is supposed to return two matches but returns every item.