简体   繁体   中英

Why can't I assign the return of a method returning a List to an ArrayList variable?

I tried:

ArrayList<Pelicula> peliculas = YIFY.obtenerPeliculasPorVenir();

being #obtenerPeliculasPorVenir :

public static List<Pelicula> obtenerPeliculasPorVenir(){

        List peliculas = null;

        try {
            peliculas = mapper.readValue(new API().peticionTexto("http://yts.re/api/upcoming.json"), new TypeReference<List<Pelicula>>(){});
        }

        catch (IOException excepcion) {
            System.out.println(excepcion.getMessage());
        }

        return peliculas;
    }
}

If ArrayList implements List why can't I do this?

Is casting the ONLY solution or I should go for another OOP approach?

Because any ArrayList is a List but not all List s are ArrayList s, for example LinkedList .

Is casting the ONLY solution or I should go for another OOP approach?

NO . The best bet is to always code to a high level interface/abstract class:

List<Pelicula> peliculas = YIFY.obtenerPeliculasPorVenir();

More info:


When should you use downcasting?

When the framework only provides access to the data as higher level classes. For example, in Java Web Development, retrieving an attribute from the session through HttpSession

//example to validate if user is logged
HttpSession session = request.getSession();
User loggedUser = (User)session.getAttribute("user"); //it returns Object
if (loggedUser == null) {
    //there's no user logged in!
    //do something about it!
}
//the user is logged, he/she can continue working...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM