1

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?

2
  • 1
    Welcome to StackOverflow. Questions asking about problems in the code must include the code, not a link to an external site like pastebin. If the code is too long, you are supposed to cut it down to only the essential part that shows the problem. Please read how to ask and how to create an MCVE. Commented Aug 1, 2015 at 8:58
  • Do you have any question about the code you have posted? Commented Aug 1, 2015 at 9:01

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.