Java 实例 - 集合中添加不同类型元素

以下实例演示了在集合类中添加不同类型的元素:

Main.java 文件

  1. import java.util.Map;
  2. import java.util.Set;
  3. import java.util.SortedMap;
  4. import java.util.SortedSet;
  5. import java.util.TreeMap;
  6. import java.util.TreeSet;
  7. import java.util.ArrayList;
  8. import java.util.Collection;
  9. import java.util.HashMap;
  10. import java.util.HashSet;
  11. import java.util.Iterator;
  12. import java.util.LinkedHashMap;
  13. import java.util.LinkedHashSet;
  14. import java.util.LinkedList;
  15. import java.util.List;
  16. public class Main {
  17. public static void main(String[] args) {
  18. List lnkLst = new LinkedList();
  19. lnkLst.add("element1");
  20. lnkLst.add("element2");
  21. lnkLst.add("element3");
  22. lnkLst.add("element4");
  23. displayAll(lnkLst);
  24. List aryLst = new ArrayList();
  25. aryLst.add("x");
  26. aryLst.add("y");
  27. aryLst.add("z");
  28. aryLst.add("w");
  29. displayAll(aryLst);
  30. Set hashSet = new HashSet();
  31. hashSet.add("set1");
  32. hashSet.add("set2");
  33. hashSet.add("set3");
  34. hashSet.add("set4");
  35. displayAll(hashSet);
  36. SortedSet treeSet = new TreeSet();
  37. treeSet.add("1");
  38. treeSet.add("2");
  39. treeSet.add("3");
  40. treeSet.add("4");
  41. displayAll(treeSet);
  42. LinkedHashSet lnkHashset = new LinkedHashSet();
  43. lnkHashset.add("one");
  44. lnkHashset.add("two");
  45. lnkHashset.add("three");
  46. lnkHashset.add("four");
  47. displayAll(lnkHashset);
  48. Map map1 = new HashMap();
  49. map1.put("key1", "J");
  50. map1.put("key2", "K");
  51. map1.put("key3", "L");
  52. map1.put("key4", "M");
  53. displayAll(map1.keySet());
  54. displayAll(map1.values());
  55. SortedMap map2 = new TreeMap();
  56. map2.put("key1", "JJ");
  57. map2.put("key2", "KK");
  58. map2.put("key3", "LL");
  59. map2.put("key4", "MM");
  60. displayAll(map2.keySet());
  61. displayAll(map2.values());
  62. LinkedHashMap map3 = new LinkedHashMap();
  63. map3.put("key1", "JJJ");
  64. map3.put("key2", "KKK");
  65. map3.put("key3", "LLL");
  66. map3.put("key4", "MMM");
  67. displayAll(map3.keySet());
  68. displayAll(map3.values());
  69. }
  70. static void displayAll(Collection col) {
  71. Iterator itr = col.iterator();
  72. while (itr.hasNext()) {
  73. String str = (String) itr.next();
  74. System.out.print(str + " ");
  75. }
  76. System.out.println();
  77. }
  78. }

以上代码运行输出结果为:

  1. element1 element2 element3 element4
  2. x y z w
  3. set3 set2 set4 set1
  4. 1 2 3 4
  5. one two three four
  6. key1 key2 key3 key4
  7. J K L M
  8. key1 key2 key3 key4
  9. JJ KK LL MM
  10. key1 key2 key3 key4
  11. JJJ KKK LLL MMM