【问题标题】:how to create an arraylist of objects of a fixed size and pass on the remaining values to the next arraylist [closed]如何创建一个固定大小的对象数组列表并将剩余值传递给下一个数组列表[关闭]
【发布时间】:2013-03-12 06:17:50
【问题描述】:

我需要创建大小为 1000 的 Arraylist,当用户输入多个值时动态创建。假设用户输入 2200 个值,则 2 个 ArrayList 每个 1000,并且必须动态创建一个 200 的 Arraylist。我该怎么办?我只知道我可以使用对象的 Arraylist。请帮忙

【问题讨论】:

  • 你能贴一些代码吗?你试过什么。?
  • 如果有用,请记住接受正确答案。

标签: java


【解决方案1】:

由于您从未指定必须初始化对象...您可以使用它。

public List<ArrayList<Object>> dynamicSizedLists(final int size) {
    List<ArrayList<Object>> retVal = new LinkedList<ArrayList<Object>>();
    final int MAX_SIZE = 1000;
    int iterations = size / MAX_SIZE;
    for(; iterations > 0; iterations--) {
        retVal.add(new ArrayList<Object>(MAX_SIZE));
    }
    retVal.add(new ArrayList<Object>(size % MAX_SIZE));

    return retVal;
}

您可以在调试器中观察到这些已通过 elementData 私有字段正确分区。

【讨论】:

    【解决方案2】:

    您可以使用ArrayList的size()方法检查大小是否达到1000,然后在另一个arraylist中添加条目。

    【讨论】:

    • 谢谢..是的,我可以使用..但是如何使用对象动态创建数组列表??
    【解决方案3】:

    您可以使用 Guavas Lists.partition 操作将所有数据列表拆分为所需大小的块 + 其余部分的一个块。一直为我工作。 Check the javadoc here if you're unsure.

    【讨论】:

    • 谢谢..但我需要创建单独的列表。
    • 它返回一个列表列表,您可以从中检索它们。 :)
    【解决方案4】:

    试试这个(注意我没有使用泛型,因为你不能有泛型数组):

    ArrayList entered = new ArrayList();
    Scanner in = new Scanner(System.in);
    while(true)
    {
        try
        {
            System.out.print("Enter a number (enter a non-number to stop)\n>");
            entered.add(in.nextInt());
        }
        catch(InputMismatchException e)
        {
            break;
        }
    }
    List[] lists = new List[entered.size() / 1000 + 1];
    int currentElement = 0;
    for(int i = 0; i < lists.length; ++i)
    {
        lists[i] = entered.subList(currentElement, (currentElement + 1000 < entered.size()) ? currentElement + 1000 : entered.size());
        currentElement += 1000;
    }
    

    【讨论】:

    • 您在哪里看到提到的数组?
    • 你能告诉我如何使用对象数组列表吗?
    • 很抱歉,在从列表中获取或删除元素时需要进行类型转换。修复了另一个错误,需要在进行下一次迭代之前向 currentElement 添加 1000。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2022-01-01
    • 2015-02-28
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    相关资源
    最近更新 更多