java 在数组列表中添加和设置之间的区别

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

difference between add and set in arraylist

javaarraylist

提问by sud0074

I need your help will you please tell me what difference between add() and set() in ArrayList. I Wrote a program uising set() and add() try to find out try to fing find out what are differences I search on the net but could not find my suitable answer

我需要你的帮助,请告诉我 ArrayList 中 add() 和 set() 之间的区别。我写了一个程序,使用 set() 和 add() 尝试找出不同之处 我在网上搜索但找不到合适的答案

public class arraylistDemo 
{

    public static void main(String[] args) throws Exception
{

        ArrayList al = new ArrayList();
        al.add(10);
        al.add("A");
        al.add("B");
        al.add(null);


        al.set(0, 11);
        System.out.println("After Add "+""+al);

        al.add(1, "AA");
        System.out.println("Using add method"+ " " +al);

        al.set(1, "AA");
        System.out.println("Using set method"+ " " +al);
    }

}

O/P- Using add method [11, AA, B, null] Using set method [11, AC, B, null]

O/P- 使用添加方法 [11, AA, B, null] 使用设置方法 [11, AC, B, null]

回答by user1803551

From List:

来自List

add(E e)

Appends the specified element to the end of this list (optional operation).

添加(E e)

将指定的元素附加到此列表的末尾(可选操作)。



add(int index, E element)

Inserts the specified element at the specified position in this list (optional operation).

添加(整数索引,E 元素)

在此列表中的指定位置插入指定元素(可选操作)。



set(int index, E element) Replaces the element at the specified position in this list with the specified element (optional operation).

set(int index, E element) 用指定的元素替换此列表中指定位置的元素(可选操作)。



Use a debugger and step one line at a time to see how your list changes. You will see that it does exactly what the Javadoc states.

使用调试器并一次执行一行以查看您的列表如何变化。您将看到它完全符合 Javadoc 的规定。

回答by Ahmed Alzubaidi

The add() method adds a value to the end of the list. set() is used to replace an existing value in a specific index in the list.

add() 方法将一个值添加到列表的末尾。set() 用于替换列表中特定索引中的现有值。