[英]Implementing List instead of ArrayList while using generics instead of raw types
經過許多帖子和建議后,我發現不是使用像ArrayList這樣的具體實現,而是應該使用List,以便在List接口的不同實現之間實現靈活性。 到目前為止,我已經看到許多程序員建議使用以下代碼:
List list = new ArrayList();
但是,這會在編譯器中發出警告,使用原始類型List和ArrayList,並且它們實際上應該參數化。
與這些警告同義,我發現有幾個帖子告訴我永遠不應該使用原始類型,並且我應該利用java提供的泛型非常方便。
就個人而言,我正在嘗試實現一個類,該類充當需要內部使用ArrayLists的2維列表結構的表。 我正在嘗試實現以下代碼行:
List<List> table;
table = new ArrayList();
table.add(new ArrayList());
在我的腦海中設想,表結構應該能夠容納多種變量類型,例如原始數據類型以及String變量類型。 我試圖實現泛型,如使用
List<List<Object>> table = new ArrayList<ArrayList<Object>>();
但是我收到了很多錯誤,因此到目前為止失敗了。
我是一個相對較新的編程,追求計算機科學專業,所以請原諒我,如果我對上面舉例說明的代碼行有任何可怕的誤解。
謝謝。
你想這樣做:
List<List<Foo>> table = new ArrayList<List<Foo>>();
table.add(new ArrayList<Foo>())
其中Foo
是存儲在表中的類型。
您希望類型和值的泛型參數相同。
import java.util.ArrayList;
import java.util.List;
public class Sample<T> {
private final int x;
private final int y;
private final List<List<T>> list;
public Sample(final int x, final int y) {
this.x = x;
this.y = y;
list = new ArrayList<>();
for(int k=0; k<y; k++) {
list.add(k, new ArrayList<T>());
}
}
public T get(final int indexX, final int indexY) {
if(indexX >= x) {
return null;
}
if(indexY >= y) {
return null;
}
return list.get(indexX).get(indexY);
}
現在你可以調用Sample<String> s = new Sample<>();
並做了。 希望它能回答你的疑問。
您應該使您的類通用,以避免警告/錯誤。 也許我寫的這個小班會幫助你:
import java.util.ArrayList;
import java.util.List;
/**
* Creates a List of Lists of the given type
* @param <T> - The type of the table elements
*/
public class Table <T> {
private final List<List<T>> data;
public Table(int rows, int cells) {
data = new ArrayList<List<T>>(rows);
for(int i=0; i<rows; i++) {
data.add(new ArrayList<T>(cells));
}
}
public static void main(String[] args) {
//create a table of strings
Table<String> table = new Table<String>(10, 10);
//do something with table
}
}
如果您希望表包含各種元素,請按以下方式創建:
Table<Object> table = new Table<Object>(10, 10);
這應該只用於演示泛型,我並不是說這是創建表的最佳方法。 另外,我正在跳過你肯定需要的其他方法的實現(比如表元素的訪問器等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.