如何在java中找到数组列表的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18890993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:58:50  来源:igfitidea点击:

How to find the size of an Array List in java?

javaarraylist

提问by Piyush Srivastava

I have to write a piece of code using ArrayList and some of its member functions.

我必须使用 ArrayList 及其一些成员函数编写一段代码。

These are the steps I have to take:

这些是我必须采取的步骤:

  1. Insert data into ArrayList;
  2. Update the array list either by insertion or by deletion;
  3. Get the size of ArrayList by using member function .length().
  1. 将数据插入到 ArrayList 中;
  2. 通过插入或删除更新数组列表;
  3. 使用成员函数.length() 获取ArrayList 的大小。

I have to execute Step 2 by using member function .clear() I have tried to execute Step 3 as well, but in my attempt, the size of the ArrayList is displayed as 1, not 0.

我必须使用成员函数 .clear() 执行步骤 2 我也尝试执行步骤 3,但在我的尝试中,ArrayList 的大小显示为 1,而不是 0。

Can you provide me with a piece of code that executes these three steps?

你能提供一段代码来执行这三个步骤吗?

回答by cb1zzly

Use arrayListName.size()for ArrayLists.

使用arrayListName.size()了的ArrayList。

Have look at http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

看看 http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

回答by Oswald

Use ArrayList.size()to determine how many elements the ArrayList contains.

使用ArrayList.size()确定 ArrayList 包含多少个元素。

回答by Moritz Petersen

Works for me:

对我有用:

    Collection<String> c = new ArrayList<String>();
    c.add("Hello");
    if (c.size() != 1) {
        throw new IllegalStateException();
    }
    c.clear();
    if (c.size() != 0) {
        throw new IllegalStateException();
    }

回答by Prabhaker A

You can use size()method to find size of the ArrayList.But I strongly recommend you to use isEmpty()method to check whether list is empty or not (instead of list.size()==0checking).
ArrayList#isEmpty

您可以使用size()method 来查找ArrayList. 但我强烈建议您使用isEmpty()method 来检查列表是否为空(而不是list.size()==0检查)。
数组列表#isEmpty

Returns true if this list contains no elements.

如果此列表不包含任何元素,则返回 true。

回答by Clover Wu

Use the .size() method..i thought that you can print the element in the array list when you thought that the all elements are cleared from the arraylist to make sure that if it is cleared.or the method .clear() just reset the elements in the arrayList.

使用 .size() 方法..我认为当您认为所有元素都从数组列表中清除以确保它是否被清除时,您可以打印数组列表中的元素。或者方法 .clear() 只是重置 arrayList 中的元素。

回答by M Martin

Just use

只需使用

int size=ArrayList.size();

int size=ArrayList.size();