-2

I want to add data to an array at runtime, but I'm getting an index out of bound exception.

String addmembers[] = new String[0];

for (int i=0; i<contactClassList.size(); i++) {
    MyClass values = contactClassList.get(i);
    String name = values.getUsernameEmail();
    Boolean isChecked = values.isChecked;
    if (isChecked) {
        addmembers[addmembers.length] = name;
    }
    System.out.println("Value of Array===" + addmembers.length);
}
Chris Moschini
  • 35,226
  • 19
  • 156
  • 186
Gaurav Arora
  • 8,092
  • 20
  • 85
  • 136

5 Answers5

7

You can't add to an array. Once you've created it, its size is fixed. You'd be better off using an ArrayList, and just calling add.

List<String> newMembers = new ArrayList<String>();
for (MyClass entry : contactClassList) {
    if (entry.isChecked) {
        newMembers.add(entry.getUsernameEmail());
    }
}
System.out.println(newMember.size());
Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
1

Your array addmembers is of size[0] which once created cannot be changed, why don't you use List, as its of dynamic size

List<String> addmembers = new ArrayList<String>();

  for(int i=0;i<contactClassList.size();i++){
    MyClass values = contactClassList.get(i);

    String name = values.getUsernameEmail();
    Boolean isChecked = values.isChecked;

    if(isChecked){
      addmembers.add(name);
    }

  System.out.println("Value of Array==="+addmembers.length);

}

Something like this will solve your problem.

1

ArrayList is the right data structure for such problem. In case you bound to use array and what you need as a grow-able then use such solutions Most memory efficient way to grow an array in Java?

Community
  • 1
  • 1
Rajnikant
  • 1,097
  • 1
  • 7
  • 22
1

Don't use Arrays for bit more amount of data. It would be better if you use ArrayList. I want to rectify your mistake and giving you this answer. You have set the String array size as 0 and trying to add elements which is not possible. So declare the array size as what you required, in your above code contactClassList.size()

                String addmembers[] = new String[contactClassList.size()];

                for(int i=0;i<contactClassList.size();i++){

                    MyClass values = contactClassList.get(i);

                    String name = values.getUsernameEmail();
                    Boolean isChecked = values.isChecked;

                    if(isChecked){

                        addmembers[addmembers.length]=name;
                    }

                    System.out.println("Value of Array==="+addmembers.length);
TNR
  • 5,814
  • 3
  • 31
  • 62
1

As per your code it will sure give you this error because you are initializing array with 0 size.

Instead of this you can use ArrayList or List<T> then you will be able to add dynamically values to it.
So it is batter to use this two instead of array.

Rahul Gokani
  • 1,648
  • 4
  • 25
  • 42