一、集合
1.Set集合
1.1基本概念
java.util.Set集合是Collection集合的子集合,与List集合平级。 该集合中元素没有先后放入次序,并且不允许重复。 该集合的主要实现类是:HashSet类和TreeSet类。其中HashSet类的底层是采用哈希表进行数据管理的。其中TreeSet类的底层是采用二叉树进行数据管理的。
1.2常用方法,代码演示
@Test public void Set(){ Set<String> set = new HashSet<>(); boolean b = set.add("two"); System.out.println("b = " + b); System.out.println(set); b = set.add("one"); System.out.println("b = " + b); System.out.println(set); b = set.add("three"); System.out.println("b = " + b); System.out.println(set); b = set.add("one"); System.out.println("b = " + b); System.out.println(set); }
1.3案例(随机生成10个1--20之间的随机数放入Set集合中并打印)
@Test public void randomSetTest(){ Random random = new Random(); Set<Integer> set = new HashSet<>(); for(int i=1; i<=10; i++){ boolean b = set.add(random.nextInt(20) + 1); if(b == false){ i--; } } System.out.println(set); while(set.size() < 10){ set.add(random.nextInt(20) + 1); } System.out.println(set); }
2.Map集合
2.1基本概念
java.util.Map集合中存取元素的基本单位是:单对元素,其中类型参数如下:K- 此映射所维护的键(Key)的类型,相当于目录。 V- 映射值(Value)的类型,相当于内容。该集合中key是不允许重复的,而且一个key只能对应一个value。该集合的主要实现类有:HashMap类和TreeMap类。
2.2常用方法
代码演示:
@Test public void hashMapTest(){ Map<Integer,String> map = new HashMap<>(); map.put(1,"张三"); map.put(2,"李四"); map.put(3,"王五"); map.put(4,"小刘"); System.out.println(map); String value = map.get(3); System.out.println("3=" + value); boolean b = map.containsKey(5); System.out.println(b); b = map.containsKey(3); System.out.println(b); b = map.containsValue("吴承恩"); System.out.println(b); b = map.containsValue("小刘"); System.out.println(b); String v = map.remove(3); System.out.println("删除的值为:" + v); v = map.remove(11); System.out.println("删除的值为:" + v); System.out.println(map); }
2.3Map集合的遍历方式
方法一:自动调用toString方法
方法二:调用keySet方法获取Map集合中所有的key
方法三:调用entrySet方法获取Map集合中所有的键值对
代码演示:
@Test public void iteratorTest(){ Map<Integer,String> map = new HashMap<>(); map.put(1,"张三"); map.put(2,"李四"); map.put(3,"王五"); map.put(4,"小刘"); //Map集合遍历,方式一 System.out.println(map); System.out.println("--------------"); //使用keySet方法遍历Map集合中的元素,方式二 Set<Integer> set = map.keySet(); System.out.println(set); for(Integer it : set){ System.out.println(it + "=" + map.get(it));//map.get()方法,返回指定键所映射的值;如果此映射不包含该键的映射关系,则返回 null。 } System.out.println("=============="); //使用entrySet方法遍历Map集合中的元素,方式三 Set<Map.Entry<Integer,String>> entries = map.entrySet(); for(Map.Entry<Integer,String> e : entries){ System.out.println(e); } }