首页 > 编程语言 > 详细

Java ArrayList add(int index, E element) example

时间:2015-07-19 11:37:12      阅读:287      评论:0      收藏:0      [点我收藏+]

Simple add() method is used for adding an element at the end of the list however there is another variant of add method which is used for adding an element to the specified index.

public void add(int index, Object element)

This method adds the element at the given index.

Example
   1: import java.util.ArrayList;
   2: public class AddMethodExample {
   3:    public static void main(String[] args) {
   4:        // ArrayList of String type
   5:        ArrayList<String> al = new ArrayList<String>();
   6:        // simple add() methods for adding elements at the end
   7:        al.add("Hi");
   8:        al.add("hello");
   9:        al.add("String");
  10:        al.add("Test");
  11:        //adding element to the 4th position
  12:        //4th position = 3 index as index starts with 0
  13:        al.add(3,"Howdy");
  14:  
  15:        System.out.println("Elements after adding string Howdy:"+ al);
  16:        //adding string to 1st position
  17:        al.add(0, "Bye");
  18:  
  19:        //Print
  20:        System.out.println("Elements after adding string bye:"+ al);
  21:    }
  22: }

Output:

Elements after adding string Howdy:[Hi, hello, String, Howdy, Test]
Elements after adding string bye:[Bye, Hi, hello, String, Howdy, Test]

Java ArrayList add(int index, E element) example

原文:http://www.cnblogs.com/hust-ghtao/p/4658375.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!