lixx3013 lixx3013 - 1 month ago 5
Java Question

Cannot add element (set) into an arraylist

I want to add a set that satisfies some conditions into an arraylist, however it cannot be added.

public void insert(List<Set<Integer>> tran){
Node left = new Node();
Node right = new Node();
List<Set<Integer>> insert_list = new ArrayList<Set<Integer>>();
for(int i = 0; i < insert_list.size(); i++){
Set<Integer> temp = insert_list.get(i);
System.out.println(temp);
Iterator itr = temp.iterator();
int value = (int)itr.next();
System.out.println(value);
if(value%2 ==0){
left.leaf.add(temp);
}
else{
right.leaf.add(temp);
}
}
System.out.println(left.leaf);
System.out.println(right.leaf);


In the main function, I called as:

Node test = new Node();
test.insert(candidate2);


This is a function under
Node
class, which its constructor looks like:

private List<Set<Integer>> leaf = new ArrayList<Set<Integer>>();
private Node left; // the node that can point to the left
private Node right; // the node that can point to the right
public Node(){
this.leaf = new ArrayList<Set<Integer>>();
left = null;
right = null;
}


Also,
System.out.println(value);
and
System.out.println(temp);
cannot be printed as well, which is really strange.

Moreover, if I change the iterator codes to
if((int)temp.toArray()[0]%2 == 0)
, it still does not work.

I have a
List<Set<Integer>> insert_list
with following attribute:
[[1, 15], [1, 58], [1, 274], [1, 326], [58, 15], [274, 15], [326, 15], [274, 58], [326, 58], [274, 326]]
. The desired output should be
[[274, 15], [326, 15], [274, 58],[326, 58], [274, 326]]
for the
left.leaf
and
[1, 15], [1, 58], [1, 274], [1, 326]]
for the
right.leaf
.

By the way, I tested these codes in the main function and it worked, I have totally no idea why it didn't work in this way.

Thanks in advance!

Edit:

The output of my function is:

[]
[]

Answer

You are confusing the method arg - tran with your local var - insert_list.

What you intended to write is:

for(int i = 0; i < tran.size(); i++){
    Set<Integer> temp = tran.get(i);

What do you need insert-list for? it seems redundant