Vahit Can Lafci
Vahit Can Lafci

Reputation: 11

Java lists issue

I'm trying to write a method that receives a List of strings, and returns subsets that contains n elements. Here is my code:

import Pack;
import java.util.List;
import java.util.ArrayList;

public class Testtt{
    public static void main(String[] args) {
        List<String> input = new ArrayList<String>();
        input.add("a");
        input.add("b");
        input.add("c");
        input.add("d");
        input.add("e");

        System.out.println(subset(input, 3));
    }

    public static List<List<String>> subset( List<String> inputlist, int n) {
        List<List<String>> output = new ArrayList<List<String>>();
        List<String> temp = new ArrayList<String>();

        for (int i = 0; i < n; i++) {
                temp = inputlist;
                System.out.println("Temp = " +temp);
                temp.remove(i);
                output.add(temp);
        }

        return output;
    }
}

Output was containing only 2 elements i decided to debug and this is the console output:

Temp = [a, b, c, d, e]
Temp = [b, c, d, e]
Temp = [b, d, e]
[[b, d], [b, d], [b, d]]

I've written temp = list at the beginning of the loop but it stays the same. Why this is happening?

Upvotes: 1

Views: 69

Answers (2)

hunter
hunter

Reputation: 4173

I can't understand the expected result here. But there are two fundamental mistakes:

  1. you modify the input list
  2. within a indexed loop you remove an element from a list. this will result in skipping elements through the iteration.

That is why this code remove a and c and e , but not b and d.

Upvotes: 1

Shriram
Shriram

Reputation: 4411

for (int i = 0; i < n; i++) {
                        temp = inputlist;
                        System.out.println("Temp = " +temp);
                        temp.remove(i);
                        output.add(temp);
                }

Here you are removing an element from temp arraylist and adding it to output arraylist. As of now you are keeping the reference of temp and making the removal on the same temp arraylist will lead to the output which you have shown. As per your program the shown output is correct. If you want it temp ouput should be storead in output arralist just create new instance of array list and store it inside output.

Upvotes: 1

Related Questions