4

My complete arrayList is not getting printed through second for loop.(print statement highlighted by comment:second loop print statement),whereas its getting printed through first for loop.

What I am trying to accomplish.:Print the objects of arraylist except characters.[print first object regardless of character or any other object].

problem I am facing:Arraylist object '2' is not getting printed on console through second for loop.

code:

import java.util.ArrayList;

public class Test1 {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    ArrayList al = new ArrayList<>();
    al.add('a');
    al.add('2');

    for(int i=0;i<al.size();i++){
        System.out.println("element enterd in for loop: "+al.get(i));
    }

    for(int i=0;i<al.size();i++){
        System.out.println("element enterd in for loop: "+al.get(i));     //second loop print statement

        if(al.get(i).toString().charAt(0)>=65 & al.get(i).toString().charAt(0)<=122){

            al.remove(i);
            continue;

                }
        }
    }

}

Help:please help me in figuring out where the issue.

5 Answers5

2

When you remove an element from an ArrayList, the indices of the following elements are decremented. Therefore, your current loop requires the following adjustment:

for(int i=0;i<al.size();i++) {
    System.out.println("element enterd in for loop: "+al.get(i));    
    if(al.get(i).toString().charAt(0)>=65 & al.get(i).toString().charAt(0)<=122) {
        al.remove(i);
        i--; // make sure you are not skipping the element following the removed element
        continue;
    }
}

BTW, converting a Character to String only to extract the first char seems very backwards.

Simply avoid using raw types:

List<Character> al = new ArrayList<>();

and

al.get(i).toString().charAt(0) > 65

can become

al.get(i) > 65
Eran
  • 387,369
  • 54
  • 702
  • 768
  • it worked very well,can you please provide document link or explanation on this please,cause I am not getting why we should decrease indices after removing elements from arraylist. – Sainath Pawar May 27 '18 at 10:14
  • @SainathPawar this is clearly stated in the Javadoc - `Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.` – Eran May 27 '18 at 10:16
  • You can do it in one line: `al.remove(i--);` – Sven May 27 '18 at 10:34
  • @Sven that's true – Eran May 27 '18 at 10:35
0

You are removing a from the list when index i = 0. Then the size of the list becomes 1 and i also becomes 1. Hence the loop condition i < al.size() is false as both i = 1 and al.size() =1. So you don't go inside the loop to print the element 2. To prevent this when you are removing an item from the list you can decrease the value of i by 1.

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
0

You can either try and use streams:

private static boolean isChar(Character x) {
    return ('a' <= x && x <= 'z' ) ||  ('A' <= x && x <= 'Z');
}

public static void main(String[] args) {
    List<Character> al = Arrays.asList('a','2','b','Z','M','4','9','g');

    al.stream().filter(x -> !isChar(x)).forEach(System.out::println);
}

output:

2
4
9
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

You can also use iterators:

    List<Character> al = new ArrayList<>();
    al.add('a');
    al.add('2');
    final Iterator<Character> iterator = al.iterator();
    while (iterator.hasNext()) {
        final Character next = iterator.next();
        System.out.println("element enterd in for loop: " + next);

        if (next.toString().charAt(0) >= 65 & next.toString().charAt(0) <= 122) {
            iterator.remove();
        }
    }

Same question is here and here.

Gat
  • 379
  • 5
  • 13
0

Please use the Following Code

  ArrayList al = new ArrayList<>();
    al.add('s');
    al.add('2');
    al.add('5');
    al.add('6');
    al.add('e');

    for (int i = 0; i < al.size(); i++) {
        System.out.println("element enterd in for loop: " + al.get(i));
    }
    System.out.println("***************\n");
    for (int i = 0; i < al.size(); i++) {
        if (i == 0) {
            System.out.println("element enterd in for loop: " + al.get(i));
        } else {
            if (!Character.isLetter(al.get(i).toString().charAt(0))) {
                System.out.println("element enterd in for loop: " + al.get(i));
            }
        }
    }
Faiz Ahmed
  • 396
  • 6
  • 13