Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Exploring the Java Collection Framework Maps

Matthew Francis
Matthew Francis
6,967 Points

How 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
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,161 Points

First 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/