Frage

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?

War es hilfreich?

Lösung

Because any ArrayList is a List but not all Lists are ArrayLists, 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...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top