Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMatthew Francis
6,967 PointsHow can this interface(Maps) be casted into another interface(List)?
//Treet is a class by the way
Treet[] treets = {treet, secondTreet};
Map<String, List<Treet>> treetsByAuthor = new HashMap<String, List<Treet>>();
for(Treet innerTreets : treets){
List<Treet> authoredTreets = treetsByAuthor.get(innerTreets.getAuthor());
..other code...
}
Could someone explain to me why the Map is able to be casted to List? shouldn't the console say "Object(Maps.get(), retruns an Object) cannot be casted to List";
And what is the purpose of casting it? what good does it do?
1 Answer
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsFirst of all there is no casting at all.
Map<String, List<Treet>> is mapping String
to List<Treet>
,
somewhat like this:
{ key -> value}
{ "string 1" -> { Treet1, Treet2}, "string 2 " -> { Treet3, Treet4} }
When you execute get("string 1")
method: it is looking for keys. In this particular case, when he finds key with
"string 1", he returns List<Treet>
in this case will be {Treet1, Treet2}
For more on casting please take a look somewhat here, e.g. https://howtoprogramwithjava.com/java-cast/