java ArrayList 中的 set()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5336491/
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-10-30 10:42:07  来源:igfitidea点击:

set() in ArrayList

javaarraylist

提问by suresh

I am new to Java, please help me.

我是 Java 新手,请帮助我。

My program is

我的程序是

import java.util.*;
import java.lang.*;
class Test
{
    public static void main(String[] args)
    {
        ArrayList al=new ArrayList();
        al.add("a");
        al.add("b");
        for(int i=1;i<=10;i++)
        {
            al.add(i);
        }
        al.remove("a");
        al.set(1,"c");
        for(int j=3;j<=al.size();j++)
        {
            al.set(j,"z");
        }

        System.out.println(al);
    }
};

in above any mistake........plz help me

以上任何错误......请帮助我

回答by Sean Patrick Floyd

a) You need to make the class public to run it:

a) 您需要公开该类才能运行它:

public class Test
{

b) the last semi-colon is a syntax errorNo it's not, it's just unnecessary noise.

b) 最后一个分号是语法错误不,不是,这只是不必要的噪音。

c) This fails with an IndexOutOfBoundsException:

c) 这失败了IndexOutOfBoundsException

for(int j = 3; j <= al.size(); j++){
    al.set(j, "z");
}

It needs to be:

它必须是:

for(int j = 3; j < al.size(); j++){
    al.set(j, "z");
}

Explanation:List Indexes are zero-based, so the highest position in a List with n elements is n-1

说明:列表索引是从零开始的,所以在一个有 n 个元素的 List 中的最高位置是 n-1



BTW, the above code can be written in a more elegant way like this:

顺便说一句,上面的代码可以用更优雅的方式写成这样:

Collections.fill(al.subList(3, al.size()), "z");

Reference:

参考:

回答by roghughe

This code will throw an IndexOutOfBounds exception because of the line:

由于以下行,此代码将引发 IndexOutOfBounds 异常:

    for (int j = 3; j <= al.size(); j++) {

to fix it, you need to change it to:

要修复它,您需要将其更改为:

    for (int j = 3; j < al.size(); j++) {

This is because the <= means that your for loop iterates over the end of the list.

这是因为 <= 表示您的 for 循环遍历列表的末尾。

回答by user unknown

List~ and Arrayindices start at 0, not 1. So if you have a list of 3 Elements, they go from index: 0, 1, 2. So you normally iterate from (i = 0; i < list.size (); ++i). Less than, not less/equal.

List~ 和 Arrayindices 从 0 开始,而不是 1。所以如果你有一个包含 3 个元素的列表,它们从索引:0, 1, 2 开始。所以你通常从 (i = 0; i < list.size (); 开始迭代。 ++i)。小于,不小于/等于。

for (int j=3; j < al.size (); j++)

回答by Lalchand

1.The semicolon in the last line

1.最后一行的分号

2.change the code from

2.更改代码

for(int j=3;j<=al.size();j++)

to

for(int j=3;j<al.size();j++)

Arraylist are always accessed from from 0th index to less than the size of the array.

Arraylist 总是从第 0 个索引到小于数组的大小访问。

回答by Yuriy Semen

I think it is necessary to change also the start index from 3 to 2:

我认为有必要将起始索引也从 3 更改为 2:

for (int j=2; j < al.size (); j++)