Update a value on specific index in Array List | Programming Hub 0

Update a value on specific index in Array List in Java

Code:

package labno1;
import java.util.ArrayList;
import java.util.Scanner;
public class ArraylistSearch {

    public static void main(String[] args) {
       
  
        Scanner n = new Scanner(System.in);
         ArrayList<String> obj = new ArrayList<String>();
         System.out.println("Enter length of Array list");
         int elem;
         elem = n.nextInt();
          System.out.println("Enter ArrayList values");
         for (int i = 0; i < elem; i++) {
             obj.add(n.next());
           
        }
         System.out.println("\nEnter the index to update value:");
        int i = n.nextInt();

        System.out.println("Enter the new value to update :");
        String item = n.next();
       
        obj.add(i, item);
      
      
                System.out.println("\nThe updated ArrayList is ");
       
        if(obj.isEmpty()) {
           
            System.out.println("ArrayList is Empty..");
        }       
        else {
           
            for( i=0; i<elem; i++) {
               
                System.out.println(obj.get(i));
            }
                }}

OutPut:

Enter length of Array list
3
Enter ArrayList values
1
2
3

Enter the index to update value:
1
Enter the new value to update :
4

The updated ArrayList is
1
4
2


Comments

  1. After all, your digestive system is an extension of your overall health. It’s your body’s home, so how you take care of it makes a huge difference to how well it functions. If your gut is happy, you feel good. If your gut is unhappy, you feel bad. ..more..

    ReplyDelete

Post a Comment

Popular posts from this blog

GUI in Java | How to make userdefined login page in graphical user interface in java

Multiple Inheritence in Java /How to inherit a class from another in Java| Programmer Hub

Search an Element in Arraylist in java | Programming Hub