splintos
splintos

Reputation: 29

Add a single element at the specified index

I'd love to exercise the CRUD principle in ArrayList in java I started today by exercising the add method however I get error when I add the methode add in static main methode I get error that the add methode should be static and when I put it static I get error by the arraylist and scanner as Strange element even wenn I add those the the static add methode After excuting the ide I get error " Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0" could someone explain me why is so

package com.company;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    Scanner scanner = new Scanner(System.in);
    List<String> arrayList1 = new ArrayList<>();

    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
        List<String> arrayList1 = new ArrayList<>();

        add();
        System.out.println(arrayList1);
    }

    public static void add(){
        Scanner scanner = new Scanner(System.in);
        List<String> arrayList1 = new ArrayList<>();

        int index=scanner.nextInt();
        String element=scanner.next();
        arrayList1.add(index,element);

    }
}

Upvotes: 0

Views: 394

Answers (2)

Joni
Joni

Reputation: 111239

When you create a list, it is initially empty. You can't add an element to index 2 if there is no item at index 0. The ArrayList class does not create elements out of nowhere for the positions 0 and 1.

You can always add an element to the end of a list, or to the beginning of a list, even if the list is empty. These are always safe:

arrayList1.add(0, element); // Add to beginning of the list
arrayList1.add(element);    // Add to end of the list

Your program has some duplicate and unused variables. For example, scanner and arrayList1 don't have to re-declared and initialized in every method - in fact, doing it will lead to bugs further down the line. You can make the class-level variables static and then you can use them in all methods:

class Main {
    static Scanner scanner = new Scanner(System.in);
    static List<String> arrayList1 = new ArrayList<>();

    public static void main(String[] args) {
        add();
        System.out.println(arrayList1);
    }

    public static void add() {
        int index = scanner.nextInt();
        String element = scanner.next();
        arrayList1.add(index, element);
    }
}

This is not the best way to program in Java, as you will learn when your studies bring you to object oriented concepts but for a beginner this is good enough

Upvotes: 1

nishgowda
nishgowda

Reputation: 21

To put it simply: You can't just add an element at a certain index (that isn't the 0th) in an uninitialized list. When you call your add function the array list is empty, which is why you're getting an IndexOutOfBoundsException error.

Upvotes: 2

Related Questions