0

I need to create method that will return permutations of arraylist. I used this method but it returns List<List<T>> and i need to get Set<Set<T>> type. Can anyone help me achieve this?

EDIT: I have tried:

public Set<Set<T>> permute() {
        List<List<T>> tmp = generatePerm(this);
        Set<Set<T>> tmpSet = new HashSet<>();
        for (List<T> el : tmp){
            tmpSet.add(new HashSet<T>(el));
        }
        return tmpSet;
    }

But it only returns one permutation.

SOLUTION:

Okay i got it. This method is in class that extends ArrayList so i simply implemented Set<T> to this class and changed return type of this method to XList<Set<T>> and it worked.

Community
  • 1
  • 1
  • The problem actually is the implementation and the purpose of a Set. A HashSet for example has no duplicates and no ordering at all. So all HashSets of your permutations are equal to each other. That's why your result (in your sample) only holds one permutation. – Peter Zberg May 30 '16 at 21:19
  • But this is a task from my University so there has to be a way of doing it. I cannot change return type. – Marcin Rejnowski May 30 '16 at 21:22

1 Answers1

1

You cannot do that, because a set is actually an unordered list (Collection). Moreover, creating a permutation requires an order. As a result, even if we assume that this is possible, you will end up with the same set each time, so you would have n equivalent sets.

Omar El Halabi
  • 2,118
  • 1
  • 18
  • 26
  • So is there any way i can achieve my goal and get `Set>` type? – Marcin Rejnowski May 30 '16 at 21:11
  • @MarcinRejnowski I guess you can use a `LinkedHashSet` in your foreach-style for loop instead of `HashSet`. `LinkedHashSet` is half way between a linked list and a hash set (it still implements `Set` ). It also memorizes the order of insertion of elements, which gives you a permutation. So you can do something like `for (List el : tmp){ tmpSet.add(new LinkedHashSet(el)); }`. – Omar El Halabi May 30 '16 at 22:09