Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me I am getting an error:

 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

This is my code:

public Collection<AdDistribution> getAdDistribution(byte srch, byte cont) throws IndexOutOfBoundsException {

    List<AdDistribution> mediums = new ArrayList<>();

    List<AdDistribution> adDistribution = new ArrayList<>();

            adDistribution.add(AdDistribution.SEARCH);

            adDistribution.add(AdDistribution.CONTENT);

            if (adDistribution.isEmpty()) {

                return null;

              }

    if (srch == 0 && cont == 0) {

        mediums = new ArrayList<>();

        mediums.set(0, adDistribution.get(0));

    }

    if (srch == 1 || cont == 1) {

        mediums = new ArrayList<>();

        if (srch == 1) {

            mediums.set(0, adDistribution.get(0));

        } else if (cont == 1) {

            mediums.set(0, adDistribution.get(1));

        }

    }

    if (srch == 1 && cont == 1) {

        mediums = new ArrayList<>();

        mediums.set(0, adDistribution.get(0));

        mediums.set(1, adDistribution.get(1));

    }

            return mediums;

}

2 Answers

0 votes
by (26.7k points)

Basically, you are trying to update the index 0 using a set method, but there is no element at this position, so first of all, you need to add an element at index 0 and then you can able to update it.

I hope this will help.

Want to know more about Java? Prefer this tutorial on Core Java Tutorial.

Want to become a Java expert? join Java Certification now!!

0 votes
ago by (1.8k points)

Error here is java.lang.IndexOutOfBoundsException: Index: 0, Size: 0, occurs is due th e reason that you are trying to use the set method on an empty ArrayList. The set method is used to replace an existing element at a specific position, but if the list is empty, there are no elements to replace, resulting in the exception.

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...