您好,欢迎访问一九零五行业门户网

在Java中如何向列表中添加元素?

我们可以使用list的add()方法向列表中添加元素。
1.使用不带索引的 add() 方法。boolean add(e e)
将指定元素追加到此列表的末尾(可选操作)。
参数e - 要附加到此列表的元素。
返回true(由 collection.add(e) 指定)。抛出unsupportedoperationexception - 如果此列表不支持添加操作。
classcastexception - 如果指定元素的类阻止将其添加到此列表中。
nullpointerexception - 如果指定的元素为 null 并且此列表不允许 null 元素。
illegalargumentexception - 如果此元素的某些属性阻止它不会被添加到此列表中。
2.使用带有索引参数的 add() 在特定位置添加元素。void add(int index, e element)
在此列表中的指定位置插入指定元素(可选操作)。将当前位于该位置的元素(如果有)以及所有后续元素向右移动(为其索引加一)。
参数index - 要插入指定元素的索引。
element - 要插入的元素。
抛出unsupportedoperationexception - 如果不支持添加操作
classcastexception - 如果指定元素的类阻止将其添加到此列表中。
nullpointerexception - 如果指定的元素为 null 并且此列表不允许 null 元素。
illegalargumentexception - 如果该元素的某些属性阻止将其添加到此列表中。
indexoutofboundsexception - 如果索引超出范围( index < 0 || index > size())。
示例以下示例显示了 add() 方法的用法 -package com.tutorialspoint;import java.util.arraylist;import java.util.list;public class collectionsdemo { public static void main(string[] args) { list<integer> list = new arraylist<>(); list.add(1); list.add(2); list.add(3); list.add(5); list.add(6); system.out.println("list: " + list); list.add(3, 4); system.out.println("list: " + list); try { list.add(7, 7); } catch(indexoutofboundsexception e) { e.printstacktrace(); } }}
输出这将产生以下结果 -
list: [1, 2, 3, 5, 6]list: [1, 2, 3, 4, 5, 6]java.lang.indexoutofboundsexception: index: 7, size: 6 at java.base/java.util.arraylist.rangecheckforadd(arraylist.java:788) at java.base/java.util.arraylist.add(arraylist.java:513) at com.tutorialspoint.collectionsdemo.main(collectionsdemo.java:22)
以上就是在java中如何向列表中添加元素?的详细内容。
其它类似信息

推荐信息