簡體   English   中英

Java類型轉換列表

[英]Java Type Casting List

我對Java泛型的工作方式有些困惑,希望有人可以幫助我更好地理解。

我正在從另一個類中調用方法。...這是我正在調用的方法。

public List<?> getPagedList() throws Exception;

當我這樣調用此方法時

myList = (List<Trade>) getPagedList();

我收到一個TypeSafety警告,說未經檢查的演員。

我嘗試將方法更改為此

<T> T getPagedList(Class<T> myClass) throws Exception;

但是我似乎無法獲得像這樣的List的類對象

getPagedList((List<Trade>).class

我有什么想法或方向可以開始學習嗎?

編輯----班級

public class Pagination{
    private static final int MAX_PAGE_LENGTH = 20;
    private static final int MAX_PAGES = 5;

    private int currentPage;
    private List list;

    public Pagination(List<?> list, String currentPage){
        this.list = list;

        if(currentPage == null)
            this.currentPage = 1;
        else
            this.currentPage = Integer.parseInt(currentPage);
    }

    public <T> List<T> getPagedList() throws Exception{
        if(currentPage * MAX_PAGE_LENGTH + MAX_PAGE_LENGTH > list.size()){
            return list.subList(currentPage*MAX_PAGE_LENGTH, list.size());
        }else{
            return list.subList(currentPage * MAX_PAGE_LENGTH, currentPage * MAX_PAGE_LENGTH + MAX_PAGE_LENGTH);
        }
    }
}

我的電話

    List<Trade> ts = (Some Code to put objects in ts)
    Pagination paging = new Pagination(ts, currentPage);
    List<Trade> ts = paging.getPagedList();

無需傳遞參數:

public class Pagination<T> {

    private static final int MAX_PAGE_LENGTH = 20;
    private static final int MAX_PAGES = 5;

    private int currentPage;
    private List<T> list;

    public Pagination(List<T> list, String currentPage){
        this.list = list;

        if (currentPage == null)
            this.currentPage = 1;
        else
            this.currentPage = Integer.parseInt(currentPage);
    }

    public List<T> getPagedList() throws Exception {
        if (currentPage * MAX_PAGE_LENGTH + MAX_PAGE_LENGTH > list.size()){
            return list.subList(currentPage * MAX_PAGE_LENGTH, list.size());
        }
        return list.subList(currentPage * MAX_PAGE_LENGTH, currentPage * MAX_PAGE_LENGTH + MAX_PAGE_LENGTH);
    }
}

那不是你想要的嗎? 這里的“魔術”是具有通用類Pagination ,其中T是整個類中相同的類型參數。

以及如何實例化它(注意Java 7中引入的菱形運算符<> ,它有助於減少冗余信息):

Pagination<Trade> p = new Pagination<>(myListOfTrades, null);

你可以這樣做

<T> List<T> getPagedList(Class<T> myClass) throws Exception;

這意味着您可以將元素的類型作為參數傳遞。

為了擴展我的評論,您可以將其用作方法的簽名:

<T> List<T> getPagedList(Class<T> type) throws Exception;

並這樣稱呼它:

List<Trade> trades = getPagedList(Trade.class);

暫無
暫無

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

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