Problem in using HashSet (Set interface)
Dear expert,
I have this code with me which gives me factorial permutations till 9 digits.
Ex ABC BCA CBA ACB BAC CAB for three digit ABCentry
I get all 9! 362880 combinations.But 10! computations results in
Java Heap Exception.
What is the ,maximum limit of HashSet and how i can avoid this error
if i am not willing to directly display on monitor instead store using
some Collection sub classes.
The code is as under
import java.util.*;
import javax.swing.*;
publicclass Combinations
{
int la,lb;//loop vars
char ch_at_pos;
char c1,c2;//variables for swapping
char var[];
String copy_token=new String("");
String combi=new String("");
static Set s=new HashSet();
//A B C D
Combinations()
{
}
Combinations(String token)//This token is assumed to carry value starting from first alphabet and moving in sequence.
{
call_method(token);
}
publicvoid call_method(String token)
{
copy_token=token;
trap_array();
while (!(combi.trim().equals(token.trim()))){
//manipulating them now as swapping entities
for (int la=0;la<=copy_token.length()-2;la++){
c1=var[la];c2=var[la+1];
swap();//Now c2=c1 and c1=c2
//reconstructing the string back
combi=copy_token.substring(0,la)+ c1 + c2 +copy_token.substring(la+2,copy_token.length());
copy_token=combi;
trap_array();
if (!s.contains(combi)){
s.add(combi);
}
}
call_method(copy_token);
}//end while
}
publicvoid swap()
{
char temp;
temp=c1;
c1=c2;
c2=temp;
}
publicstaticvoid print()
{
System.out.println("\n");
Iterator a =s.iterator();
while (a.hasNext())
{
System.out.print(a.next()+" ");
}
System.out.println("\n");
System.out.println("Total size : "+s.size());
System.out.println();
}
publicvoid trap_array()
{
var=newchar[25];//assuming this length to be maximum.
for (la=0;la<=copy_token.length()-1;la++){
ch_at_pos=copy_token.charAt(la) ;
var[la]=ch_at_pos;
}//collecting string tokens as chars
}
publicstaticvoid main(String args[])
{
Set vadd=new HashSet();
String inputval=JOptionPane.showInputDialog("Please enter a word (any length but nominal:) :");
if (inputval.length()==1){
JFrame fr=new JFrame();
JOptionPane.showMessageDialog(fr,"One unit length is its own factorial");
System.exit(0);
}
new Combinations(inputval);
int n=factorial(inputval.length());
while (s.size() < n){
Iterator a =s.iterator();
while (a.hasNext())
{
String s1=new String(a.next().toString());
vadd.add(String.valueOf(s1));
}
Iterator b =vadd.iterator();
while (b.hasNext()){
new Combinations(String.valueOf(b.next()));
}
}
print();
}
staticint factorial (int x)
{
int z=1;
for (int y=1;y<=x;y++){
z=z*y;
}
return(z);
}
}//End class
Can anyone tell me ?

