Java - hashset - Asked By rocky sharma on 16-Mar-12 03:25 PM

i have a question abt Hashset
in my program here



Set<String> set=new HashSet<String>(abc);
for(String s:set)
{
System.out.println(""+s);
}
}
in first line "abc" is a string variable and compiler is giving error...abt the constructor argument..

and this 
Collection< String > collection 

Set< String > set = new HashSet< String >( collection );

this code is running 

i wanna know that how can i directly put and string value in the HashSet ?
plz help me  
D Company replied to rocky sharma on 19-Mar-12 11:52 AM
Where u have define abc, and how u declare it? use this way to set string.

Set<String> yourStringName = new HashSet<String>()
{{
    this.add("abc");
 
}}

let me know if u still face problem

Regards
D


[)ia6l0 iii replied to rocky sharma on 19-Mar-12 10:04 PM
In Java, the hashset takes a Collection. Hence, your first piece of code does not compile. It is behavior by design.
And I am also aware that it takes a int as a constructor parameter, but not a plain string. 

So the following line would not work.
Set<String> set=new HashSet<String>(abc);

Change it like below.
Set<String> set=new HashSet<String>();
set.add(abc);


Or using anonymous functions:
Set<String> set=new HashSet<String>() {{
    add(abc);
}};

Hope this helps.