Foreach loop error... undefined for the type
I'm try开发者_如何学JAVAing to do a foreach loop with an ArrayList... here's the story...
I have an ArrayList:
ArrayList<Album> coll = new ArrayList<Album>();
This contains information about a number of albums that make up a collection/library...
The Album class contains a method that returns the album name in string.
I'm basically trying to find out if album already exists or not with a foreach loop.
I have this method:
public Boolean findAlbumByName(ArrayList<Album> albumList, String name){
for (Album album : albumList)
{
if (album.getName().equals(name))
{
return true;
}
}
return false;
}
The problem occurs when I try to do this statement:
if(findAlbumByName(coll, 'example song') == false)
{
// code here
}
It has an error that reads: The method findAlbumByName(ArrayList<Album>, String) is undefined for the type Album.
Any help or clue would be highly appreciated. Thank you.
You need to change
'example song'
to"example song"
And you may want to change
public Boolean findAlbumByName
to
public boolean findAlbumByName ^
Another way of writing
condition == false
is to negate the condition, like!condition
.
Here is an example implementation if you're still stuck.
The method findAlbumByName(ArrayList<Album>, String) is undefined for the type Album
means that you are trying to call the method from the Album
class, even though you have not defined the method on that class. To get your code to work, you need to do two things:
- Move the method into the
Album
class (if that's where it belongs) - Change your string so that it uses double-quotes (
"
) rather than single quotes ('
).
Once you do that, your method should work just fine.
Maybe with the full code it would be easier.. By the way, given that your function implements a use-case (i.e. it's a general function that it's not called on any instance of the class Album in particular), shouldn't it be static
??
`public static boolean findAlbumByName(ArrayList albumList, String name);
Also, have you considered using the boolean contains(Object elem)
of ArrayList? Remember to override the boolean equals(Object o)' in
Almbum` though!!
public Boolean findAlbumByName(ArrayList<Album> albumList, String name)
should be (notice lower case boolean)
public boolean findAlbumByName(ArrayList<Album> albumList, String name)
and call it this way (notice qualifying a string with double quotes - single quote is for char types):-
if(!findAlbumByName(coll, "example song"))
Also you should consider using an interface on the left hand side in your ArrayList declaration. Example:
List<Album> coll = new ArrayList<Album>();
if ( ! findAlbumByName(coll, 'example song') )
{
}
精彩评论