0

Suppose that I have an Array list of Array lists:

A = [2, 5, 6], [1, 6, 1], [], [7, 7], [4, 2], [9, 3]]

and I want to split them at the index where the element of the array list has the size of 0 so that it will look like this

x = [[2, 5, 6], [1, 6, 1]]
y = [[7, 7], [4, 2], [9, 3]]

but whenever I run my loop it comes out like this:

for(int i = 0; i < A.size(); i++) {
    ArrayList temp= A.get(i);
    int size = temp.size();
    if(size != 0) {
       x.add(temp);
    }
       y.add(temp);
    }
x = [[2, 5, 6], [1, 6, 1], [7, 7], [4, 2], [9, 3]]
y = [[2, 5, 6], [1, 6, 1], [], [7, 7], [4, 2], [9, 3]]

Can anyone please help me figure this out?

sadCoder23
  • 13
  • 2

4 Answers4

1

You logic is off. Currently you are avoiding writing the empty list into x; other than that you always write to both x and y.

You can have a boolean to say which list the data must be written to. Once you see a list with size 0, switch the flag.

boolean writeToX = true;

for(int i = 0; i < A.size(); i++) {
    ArrayList temp= A.get(i);
    int size = temp.size();
    if(size == 0) {
       writeToX = false;
       continue;
    }
    if (writeToX) {
        x.add(temp);
    } else {
        y.add(temp);
    }
      
}

Sidenote: Avoid using raw types.

What is a raw type and why shouldn't we use it?

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
1

You need to keep track of the destination array like this:

boolean addToX = true;

for(ArrayList temp : A) {
  if(temp.isEmpty()) {
    addToX = false;  
  } else if(addToX) {
    x.add(temp);
  } else {
    y.add(temp);
  }
}
andbi
  • 4,426
  • 5
  • 45
  • 70
0

Try this, add a boolen flag to identify :-

    boolean flag=false;
    for(int i = 0; i < A.size(); i++) {
        ArrayList temp= A.get(i);
        int size = temp.size();
        if(size != 0 && flag==false) {
           x.add(temp);
        }else if(size==0) {
           flag=true;
        }else if(size != 0 && flag==true){
            y.add(temp);
        }
Gaurav Dhiman
  • 953
  • 6
  • 11
0

it is normal because you are just not putting the empty element to x but you are putting all other elements to x and y. You can have a boolean parameter, such as isNullArrayCome and check it on every iteration. Here it is

boolean isNullArrayCome = false;
for(int i = 0; i < A.size(); i++) {
    ArrayList temp= A.get(i);
    int size = temp.size();
    if(size == 0 ) {
      isNullArrayCome = true;
     }
     if(!isNullArrayCome){
       x.add(temp);
     } else {
       y.add(temp);
     }
}