簡體   English   中英

為什么我不能分配將List返回到ArrayList變量的方法的返回值?

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

我試過了:

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

正在#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;
    }
}

如果ArrayList 實現 List為什么我不能這樣做?

僅使用解決方案,還是應該采用另一種OOP方法?

因為任何ArrayList都是List但並非所有List都是ArrayList ,例如LinkedList

是僅使用解決方案,還是應該采用另一種OOP方法?

不行 最好的選擇是始終編碼為高級接口/抽象類:

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

更多信息:


什么時候應該使用向下轉換?

當框架僅提供對數據的訪問作為更高級別的類時。 例如,在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...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM