Re: return a Collection (Set or List)
Roedy Green wrote:
On Tue, 13 May 2008 11:29:57 GMT, thufir <hawat.thufir@gmail.com>
wrote, quoted or indirectly quoted someone who said :
found : java.util.Collection<a00720398.data.Guest>
required: java.util.List<a00720398.data.Guest>
guests = console.scanFile(new File("Guests.txt"), new GuestFactory
());
^
All Lists are Collections but not all Collections are Lists. Java
insists on an explicit cast when the conversion might conceivably
fail, e.g. Collection -> List.
You need to have your method return a List<Guest> or you need to cast
the assignment with:
guests = (List <Guest>)xxxx;
This works, but is a little hackish. As you say, sometimes you will
return a Set. The above will fail if you do return a set.
Consider substituting two methods for this one. "getAsList" and
"getAsSet" Then the caller can indicate which type is desired and always
receive the correct type.
You can use built-in methods to transform Lists to Sets and vice versa.
It's usually just a couple of method calls. Actually you could do
this externally too and not have to touch your class. Always get a
list. If you need a set, just transform the List into a Set.
You could always just:
List myList
myList = getSomeList();
Set mySet = new SomeSet();
mySet.addAll( myList );
This feels a bit safer to me than casting something that might fail.