【问题标题】:Implementing List instead of ArrayList while using generics instead of raw types在使用泛型而不是原始类型时实现 List 而不是 ArrayList
【发布时间】:2015-02-14 22:04:24
【问题描述】:

在浏览了很多帖子和建议后,我发现与其使用 ArrayList 这样的具体实现,不如使用 List,以允许 List 接口的不同实现之间具有灵活性。到目前为止,我看到很多程序员建议下面这行代码:

List list = new ArrayList();

但是,这会在编译器中给出使用原始类型 List 和 ArrayList 的警告,并且它们实际上应该被参数化。

与这些警告的同义词是,我发现有几篇帖子告诉我,不应该使用原始类型,并且我应该利用 java 提供的方便的泛型。

就个人而言,我正在尝试实现一个充当表格的类,该表格需要一个二维列表结构,其中 ArrayLists 在内部使用。 我正在尝试实现以下代码行:

List<List> table;
table = new ArrayList();
table.add(new ArrayList());

在我的脑海中设想,表结构应该能够容纳多种变量类型,例如原始数据类型以及字符串变量类型。我试图实现泛型,例如使用

List<List<Object>> table = new ArrayList<ArrayList<Object>>();

但我收到了很多错误,因此到目前为止失败了。

我对编程比较陌生,攻读计算机科学专业,如果我对上面举例说明的代码行有任何可怕的误解,请原谅我。

谢谢。

【问题讨论】:

  • 你仍然在这里使用原始类型List&lt;List&gt;。阅读this,它解决了你最后的sn-p代码。
  • 这应该是 List&lt;List&lt;Object&gt;&gt; table = new ArrayList&lt;List&lt;Object&gt;&gt;(); 并且您可能正在寻找 List&lt;List&lt;?&gt;&gt; table = new ArrayList&lt;List&lt;?&gt;&gt;(); 但这仍然只是存储 Object 而不一定是 String 或任何东西。
  • 我现在真的明白了。谢谢。

标签: java list generics arraylist parameterized


【解决方案1】:
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&lt;String&gt; s = new Sample&lt;&gt;(); 并完成。希望它能回答您的查询。

【讨论】:

  • 非常感谢您的努力。我现在明白了。
【解决方案2】:

您应该使您的类通用以避免警告/错误。也许我写的这个小班会帮助你:

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);

这应该只用于演示泛型,我并不是说这是创建表的最佳方式。此外,我将跳过您肯定需要的其他方法的实现(例如表格元素的访问器等)。

【讨论】:

    【解决方案3】:

    你想这样做:

    List<List<Foo>> table = new ArrayList<List<Foo>>();
    table.add(new ArrayList<Foo>())
    

    Foo 是存储在表中的类型。

    您希望类型和值的泛型参数相同。

    【讨论】:

    • 它看起来很简单,但我无法弄清楚。我感到宽慰的是,我不会收到更多这些警告并且仍然使用泛型。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-03-15
    • 2016-01-14
    • 2020-04-17
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多