title: Algorithm to find powerset of {1,2,3}
body: <p>I think i'm finding this a little confusing because i've never really used Java sets. Could someone please try and show me (preferably by explaining how the powerset is gradually being created) in the following code (ps i got this code from a post on stackoverflow, so credit goes to that person):</p>
  
  <pre><code>public static void main(String[] args) {
          Set&lt;Integer&gt; mySet = new HashSet&lt;Integer&gt;();
          mySet.add(1);
          mySet.add(2);
          mySet.add(3);
          for (Set&lt;Integer&gt; s : powerSet(mySet)) {
              System.out.println(s);
          }
  
      }
  
      public static &lt;T&gt; Set&lt;Set&lt;T&gt;&gt; powerSet(Set&lt;T&gt; originalSet) {
          Set&lt;Set&lt;T&gt;&gt; sets = new HashSet&lt;Set&lt;T&gt;&gt;();
  
          //If the input is empty, add the empty set and return
          if (originalSet.isEmpty()) {
              sets.add(new HashSet&lt;T&gt;());
              return sets;
          }
  
          //Put the originalSet into an arraylist
          List&lt;T&gt; list = new ArrayList&lt;T&gt;(originalSet);
  
          //Get the first element
          T head = list.get(0);
  
          //Get everything but the first element and put into a set
          Set&lt;T&gt; rest = new HashSet&lt;T&gt;(list.subList(1, list.size()));
  
          //For each element in the set above
          for (Set&lt;T&gt; set : powerSet(rest)) {
  
              //Create a new set
              Set&lt;T&gt; newSet = new HashSet&lt;T&gt;();
  
              //Add the head
              newSet.add(head);
  
              //Add the rest
              newSet.addAll(set);
  
              //Add all of newset to the result
              sets.add(newSet);
  
              //Add the current element
              sets.add(set);
          }
          return sets;
      }
  </code></pre>