为什么我不能将返回List的方法返回给ArrayList变量?

die*_*lar 1 java interface list arraylist

我试过了:

ArrayList<Pelicula> peliculas = YIFY.obtenerPeliculasPorVenir();
Run Code Online (Sandbox Code Playgroud)

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果ArrayList 实现 List为什么我不能这样做?

是铸造唯一的解决方案还是我应该采取另一种OOP方法?

Lui*_*oza 8

因为任何ArrayList一个List,但不是所有的Lists为ArrayListS,例如LinkedList.

是铸造唯一的解决方案还是我应该采取另一种OOP方法?

.最好的办法是始终编写一个高级接口/抽象类:

List<Pelicula> peliculas = YIFY.obtenerPeliculasPorVenir();
Run Code Online (Sandbox Code Playgroud)

更多信息:


你什么时候应该使用向下转换?

当框架仅提供对更高级别类的数据的访问.例如,在Java Web Development中,从会话中检索属性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...
Run Code Online (Sandbox Code Playgroud)