Write a java program to insert an element into the array list at the first position.

Java Collection, ArrayList Exercises: Insert an element into the array list at the first position

Last update on December 14 2021 06:21:53 (UTC/GMT +8 hours)

Java Array Exercises: Insert an element into an array

Last update on December 13 2021 06:23:28 (UTC/GMT +8 hours)

Write a Java program to insert an element into the array list at the first position

July 29, 2021 by

Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

import java.util.*; public class Javacollectionexcercise { public static void main(String[] args) { List<String> Stringslist = new ArrayList<String>(); Stringslist.add("Audi"); Stringslist.add("BMW"); Stringslist.add("Bugatti"); Stringslist.add("Ford"); Stringslist.add("Honda"); Stringslist.add("Hyundai"); System.out.println(Stringslist); Stringslist.add(0, "Ferrari"); Stringslist.add(7, "Fiat"); System.out.println(Stringslist); } }

How to insert an element at beginning of the ArrayList in Java?

When we add elements to the ArrayList using theadd method, they are inserted at the end of the ArrayList. To insert element at the beginning or start of the ArrayList, use the overloaded add method of ArrayList which also accepts anindex parameter wherethe element needs to be inserted.

1
public void add(int index, E element)

This method inserts the element at the specified index in the ArrayList. If there is any element exists at the specified position, it shifts the existing elements along with any subsequent elements to the right (means increases their index by 1).

Java ArrayList insert an element at the beginning example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.javacodeexamples.collections.arraylist;
import java.util.ArrayList;
public class ArrayListInsertElementExample {
public static void main(String[] args) {
//create new ArrayList
ArrayList<String> aListNumbers
= new ArrayList<String>();
//we are going to add some numbers to ArrayList
aListNumbers.add("One");
aListNumbers.add("Two");
aListNumbers.add("Three");
/*
* To insert element at beginning of ArrayList
* use add method of ArrayList class with index 0
*/
aListNumbers.add(0, "Zero");
System.out.println("Element added at beginning of ArrayList");
//print ArrayList
System.out.println(aListNumbers);
}
}

Output

1
2
Element added at beginning of ArrayList
[Zero, One, Two, Three]

As you can see from the output, we specified index as 0 in the add method to insert element at the start of the ArrayList. List automatically shifted all the existing elements by increasing their index by 1.

Java Program To Insert an Element at Specified Position in an Array

In this tutorial, we will learn how to add an element to a given position in an array. The easiest way to do this is by shifting the elements and then inserting the element at a specific position. But before moving forward, if you are not familiar with the concepts of the array, then do check the article Arrays in Java.

Input:

Original Array: 5 7 2 3 1 5 6 8

Element: 55

Position: 2

Output: 5 7 55 2 3 1 5 6 8

How to Insert an element at a specific position in an Array in Java

An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in Java.
Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.

Approach 1:
Here’s how to do it.

  1. First get the element to be inserted, say x
  2. Then get the position at which this element is to be inserted, say pos
  3. Create a new array with the size one greater than the previous size
  4. Copy all the elements from previous array into the new array till the position pos
  5. Insert the element x at position pos
  6. Insert the rest of the elements from the previous array into the new array after the pos

Below is the implementation of the above approach:

Java




// Java Program to Insert an element
// at a specific position in an Array
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to insert x in arr at position pos
public static int[] insertX(int n, int arr[],
int x, int pos)
{
int i;
// create a new array of size n+1
int newarr[] = new int[n + 1];
// insert the elements from
// the old array into the new array
// insert all elements till pos
// then insert x at pos
// then insert rest of the elements
for (i = 0; i < n + 1; i++) {
if (i < pos - 1)
newarr[i] = arr[i];
else if (i == pos - 1)
newarr[i] = x;
else
newarr[i] = arr[i - 1];
}
return newarr;
}
// Driver code
public static void main(String[] args)
{
int n = 10;
int i;
// initial array of size 10
int arr[]
= { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// print the original array
System.out.println("Initial Array:\n"
+ Arrays.toString(arr));
// element to be inserted
int x = 50;
// position at which element
// is to be inserted
int pos = 5;
// call the method to insert x
// in arr at position pos
arr = insertX(n, arr, x, pos);
// print the updated array
System.out.println("\nArray with " + x
+ " inserted at position "
+ pos + ":\n"
+ Arrays.toString(arr));
}
}
Output:

Initial Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Array with 50 inserted at position 5: [1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]

Approach 2:
Here’s how to do it.

  1. First get the element to be inserted, say element
  2. Then get the position at which this element is to be inserted, say position
  3. Convert array to ArrayList
  4. Add element at position using list.add(position, element)
  5. Convert ArrayList back to array and print

Below is the implementation of the above approach:

Java




// Java Program to Insert an element
// at a specific position in an Array
// using ArrayList
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AddElementAtPositionInArray {
// Method to add element at position
private static void addElement(
Integer[] arr, int element,
int position)
{
// Converting array to ArrayList
List<Integer> list = new ArrayList<>(
Arrays.asList(arr));
// Adding the element at position
list.add(position - 1, element);
// Converting the list back to array
arr = list.toArray(arr);
// Printing the original array
System.out.println("Initial Array:\n"
+ Arrays.toString(arr));
// Printing the updated array
System.out.println("\nArray with " + element
+ " inserted at position "
+ position + ":\n"
+ Arrays.toString(arr));
}
// Drivers Method
public static void main(String[] args)
{
// Sample array
Integer[] arr = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10 };
// Element to be inserted
int element = 50;
// Position to insert
int position = 5;
// Calling the function to insert
addElement(arr, element, position);
}
}
Output: Initial Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Array with 50 inserted at position 5: [1, 2, 3, 4, 50, 5, 6, 7, 8, 9, 10]




Article Tags :
Java Programs
Java-Array-Programs
Read Full Article

How to Add an Element at Particular Index in Java ArrayList?

ArrayList.add() method is used to add an element at particular index in Java ArrayList.

Syntax:

public void add(int index, Object element) ;

Parameters:

  • index -position at which the element has to be inserted. The index is zero-based.
  • element – the element to be inserted at the specified position.

Exception: throws IndexOutOfBoundsException which occurs when the index is trying to be accessed which isn’t there in the allocated memory block. In java, this exception is thrown when a negative index is accessed or an index of memory space. Here particularly when an index greater than the size of ArrayList is trying to be fetched or the insertion of an element at an index greater than size() of ArrayList is fetched.

Example:



For a list of string

list=[A,B,C]

list.add(1,”D”);

list.add(2,”E”);

list=[A,D,E,B,C]

For a list of integers

LIST=[1,2,3]

list.add(2,4);

list=[1,2,4,3]

Implementation:

Java




// Adding an Element at Particular
// Index in Java ArrayList
import java.io.*;
import java.util.ArrayList;
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList
ArrayList<String> list = new ArrayList<>();
// Adding elements to ArrayList
// using add method for String ArrayList
list.add("A");
list.add("B");
list.add("C");
/* Index is zero based */
// 3 gets added to the 1st position
list.add(1, "D");
// 4 gets added to the 2nd(position)
list.add(2, "E");
// Displaying elements in ArrayList
System.out.println(list);
}
}


Output [A, D, E, B, C]

Article Tags :
Java
Java Programs
Java-ArrayList
Practice Tags :
Java
Read Full Article

Java.util.ArrayList.add() Method

Advertisements

Previous Page
Next Page

Video liên quan

Postingan terbaru

LIHAT SEMUA