fork download
  1. package org.JavaIncloud.java;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. public class SetShowCase
  7. {
  8. public static void main(String...JavaInCloud)
  9. {
  10. /*create an ArrayList(a class implements List) and assign
  11. * to List as we can not create object for List interface*/
  12. Set<String> animals = new HashSet<String>();
  13.  
  14. //Store some animal name to the collection of animal object(Here String)
  15. animals.add("Tiger");animals.add("Monkey");
  16. animals.add("Cow");animals.add("Cat");
  17. animals.add("Dog");
  18.  
  19. /*print the Set, it'll print the animal name, as internally ArrayList overwrite toString()*/
  20. System.out.println("Animal Name>>"+animals);
  21. //output:Animal Name>>[Cat, Dog, Tiger, Monkey, Cow]
  22.  
  23. /*there is not get() method for Set hence it'll not work, instead it'll give you a compilation error*/
  24. //System.out.println(Animal.get(3));
  25.  
  26. /*Retrieve the element from set.
  27. * This is how for-each loop works if you want then you can use Iterator also
  28. * Get the iterator from HashSet and iterate it. Iterator<String> iterator = animals.iterator();*/
  29. for (String animal : animals)
  30. {
  31. System.out.print(animal+",");
  32. }
  33. //output: Cat,Tiger,Dog,Monkey,Cow,
  34.  
  35. /*If you are bothering about order of the set then you have go for LinedHashSet and TreeSet.
  36. * HashSet makes no guarantees as to the iteration order of the set; in particular,
  37. * it does not guarantee that the order will remain constant over time. This class permits the null element.*/
  38. }
  39. }
  40.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:6: error: class SetShowCase is public, should be declared in a file named SetShowCase.java
public class SetShowCase
       ^
1 error
stdout
Standard output is empty