Java. util. ArrayList. set () method instance, java. util. arraylist

Source: Internet
Author: User

[Switch] Java. util. ArrayList. set () method instance, java. util. arraylist

Java. util. ArrayList. set (int index, E element)Replace and specify the elements at the specified position in this list.

Statement

The following is the declaration of the java. util. ArrayList. set () method.

public E set(int index, E element)
Parameters
  • Index -- replace the index element.

  • Element -- the element to be stored at the specified position.

Return Value

This method returns the element before the specified position.

Exception
  • IndexOutOfBoundsException -- if the index is out of the range

Example

The following example demonstrates how to use java. util. Arraylist. set.

package com.yiibai;import java.util.ArrayList;public class ArrayListDemo {   public static void main(String[] args) {            // create an empty arraylist with an initial capacity      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);      // use add() method to add elements in the list      arrlist.add(15);      arrlist.add(20);      arrlist.add(25);      arrlist.add(22);      // let us print all the elements available in list      for (Integer number : arrlist) {        System.out.println("Number = " + number);      }      // inserting elment 55 at 3rd position      arrlist.set(2,55);        // let us print all the elements available in list      System.out.println("Printing new list:");      for (Integer number : arrlist) {        System.out.println("Number = " + number);      }    }}

Let's compile and run the above program, which will produce the following results:

Number = 15Number = 20Number = 25Number = 22Printing new list:Number = 15Number = 20Number = 55Number = 22

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.