Getting Started with Java (three) - The collection shall speak

Collection (or called container) is the core Java knowledge, it has a deep depth. We are not here to design deep, just as get started, understand the venue and various sets of source articles. Ok, what began to introduce ...

Why Java collections born

We know that, Java is an object-oriented programming language, which means the program there are a lot of objects. This time the question came up, how we are better off storing and manipulating objects it? If you can understand this, then you will know "why the collection is born" answer to this question.

Sum up by saying: Java provides us with a tool (the set) to store and facilitate our operations more Java objects

Getting Started with Java collections learning

The purpose Java collections is easy to operate multiple objects at the same time, it offers a range of API for us to operate. Therefore, when we begin to learn Java collection is more to learn the use of these API's .

API Java collections for use after a certain understanding, we should from the object-oriented point of view to understand it. Why abstract multiple interfaces, as well as what each interface features.

We can summarize several common implementation class, these common implementation class we have to know what its data structure, when to use this class.

To understand object-oriented

At the same time, you also need to learn and understand the data structure:

data structure

After completing the above, we have mastered the basic set of commonly used data structures, we will know how to choose the appropriate collection container to store our object. In short, after completing data structure of the common implementation class, their usage scenarios have a more clear understanding .

Introduction to Java collection classes

Java is a very large collection of knowledge, did not talk much, feeling under the map:

Java collections

  1. Java collections root interface is Collection , it inherits the interface Iterable iteration
  2. List Interface and Set interface extends the Collection interface
  3. Map interface is independent of the interface, and not inherit the Collection interface
  4. List接口常用的实现类有:ArrayList、LinkedList、Vector
  5. Set接口常用的实现类有:HashSet、LinkedHashSet、TreeSet
  6. Map接口常用的实现类有:HashMap、HashTable、TreeMap

Java容器可分为两大类:

  • Collection
    • List
      • ArrayList
      • LinkedList
      • Vector(了解,已过时)
    • Set
      • HashSet
        • LinkedHashSet
      • TreeSet
  • Map
    • HashMap
      • LinkedHashMap
    • TreeMap
    • ConcurrentHashMap
    • Hashtable(了解,,已过时)

Iterator迭代器

迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小

我们可以发现一个特点,上述所有的集合类,除了Map系列的集合,Collection集合都实现了Iterator接口。我们可以在源码中追溯到集合的顶层接口,比如Collection接口,可以看到它继承的是类Iterable。

它是Java集合的顶层接口(不包括Map系列的集合,Map接口是Map系列集合的顶层接口)

所以除了Map系列的集合,我么都能通过迭代器来对集合中的元素进行遍历。

Map集合的子类可以用keyset()方法转换成Set集合遍历

Iterable迭代器一共4个方法:

  • hasNext():判断下个迭代器是否还有下一个元素

  • next():返回下一个元素的值,并且把自身offset移动下一位

  • remove():这个可以删除用这个迭代器集合中的元素(注意如果删除之后还是前面获得的迭代器,你会发现原来的迭代器还是没变,得重新获得删除元素之后的迭代器)

  • forEachRemaining:1.8的新方法 可以直接遍历迭代器剩下的元素,如果从最开始的话就是遍历所有的迭代器

补充: 还有一个ListIterator接口,它继承了Iterator接口,但只能用于List集合。它是Iterator接口的升级版,里面除了Iterator含有的功能外,还具有一些其他的功能。Iterator遍历集合元素时,只能单向遍历,而ListIterator可以双向进行遍历、添加元素、设置元素

当使用Iterator对集合元素进行迭代时,Iterator并不是把集合元素本身传给了迭代变量,而是把集合元素的值传给了迭代变量(就如同参数传递是值传递,基本数据类型传递的是值,引用类型传递的仅仅是对象的引用变量),所以修改迭代变量的值对集合元素本身没有任何影响。
下面的程序演示了这一点:

public class IteratorExample {
    public static void main(String[] args){
        List<String> list =Arrays.asList("java语言","C语言","C++语言");
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            String next = iterator.next();//集合元素的值传给了迭代变量,仅仅传递了对象引用。保存的仅仅是指向对象内存空间的地址
            next ="修改后的";
            System.out.println(next);
        }
        System.out.println(list);
    }
}

输出结果:

修改后的
修改后的
修改后的
[java语言, C语言, C++语言]

Collection接口

Collection的作用就是规定了一个集合有哪些基本的操作。 这里主要是插入数据,清空数据,是否包含,是否相等,集合里的数据个数和转化成熟组这几种操作。

接口中定义的方法:

Collection interface method

Collection接口是Set、List、Queue的父接口。下面逐一介绍:

Set集合

Set集合与Collection集合基本相同,没有提供任何额外的方法。实际上Set就是Collection,只是行为略有不同(Set不允许包含重复元素)。
Set集合不允许包含相同的元素,如果试图把两个相同的元素加入同一个Set集合中,则添加操作失败,add()方法返回false,且新元素不会被加入。

List集合

List集合代表一个元素有序、可重复的集合,集合中每个元素都有其对应的顺序索引。List集合允许使用重复元素,可以通过索引来访问指定位置的集合元素 。List集合默认按元素的添加顺序设置元素的索引,例如第一个添加的元素索引为0,第二个添加的元素索引为1......
List作为Collection接口的子接口,可以使用Collection接口里的全部方法。而且由于List是有序集合,因此List集合里增加了一些根据索引来操作集合元素的方法:

  • void add(int index, Object element): 在列表的指定位置插入指定元素(可选操作)
  • boolean addAll(int index, Collection c) : 将集合c 中的所有元素都插入到列表中的指定位置index处
  • Object get(index):返回列表中指定位置的元素
  • int indexOf(Object o): 返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1
  • int lastIndexOf(Object o):返回此列表中最后出现的指定元素的索引;如果列表不包含此元素,则返回 -1
  • Object remove(int index): 移除列表中指定位置的元素
  • Object set(int index, Object element):用指定元素替换列表中指定位置的元素
  • List subList(int fromIndex, int toIndex): 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的所有集合元素组成的子集
  • Object[] toArray(): 返回按适当顺序包含列表中的所有元素的数组(从第一个元素到最后一个元素)

除此之外,Java 8还为List接口添加了如下两个默认方法:

  • void replaceAll(UnaryOperator operator):根据operator指定的计算规则重新设置List集合的所有元素
  • void sort(Comparator c):根据Comparator参数对List集合的元素排序

Queue集合

Queue用户模拟队列这种数据结构,队列通常是指“先进先出”(FIFO,first-in-first-out)的容器。队列的头部是在队列中存放时间最长的元素,队列的尾部是保存在队列中存放时间最短的元素。新元素插入(offer)到队列的尾部,访问元素(poll)操作会返回队列头部的元素。通常,队列不允许随机访问队列中的元素。

接口中定义的方法:

Queue Interface Methods

Map集合

Map用户保存具有映射关系的数据,因此Map集合里保存着两组数,一组值用户保存Map里的key,另一组值用户保存Map里的value,key和value都可以是任何引用类型的数据。Map的key不允许重复,即同一个Map对象的任何两个key通过equals方法比较总是返回false。
如下图所描述,key和value之间存在单向一对一关系,即通过指定的key,总能找到唯一的、确定的value。从Map中取出数据时,只要给出指定的key,就可以取出对应的value。

Map model

Map集合包括Map接口以及Map接口的所有实现类。Map集合具有以下特点:

  1. Map接口并没有继承Collection接口,提供的是key到value的映射
  2. Map中不能包含相同的key

Map接口常用的实现类有:HashMap、HashTable、TreeMap。

我们先看下如下示例了解下Map集合的用法:

package collection;

import java.util.*;

public class Muster {
    public static void main(String[] args) {
        Map<Integer, String> platformMap = new HashMap<>();
        platformMap.put(1, "博客园");
        platformMap.put(2, "掘金");
        platformMap.put(3, "微信公众号");
        platformMap.put(4, "个人博客");

        // 尝试添加重复Map
        platformMap.put(4, "个人博客");

        // 获取所有的key
        Set<Integer> keys = platformMap.keySet();
        for (Integer integer : keys) {
            System.out.println("Key:" + integer + ",Value:" + platformMap.get(integer));
        }
    }
}

以上代码的输出结果为:

Key:1,Value:博客园
Key:2,Value:掘金
Key:3,Value:微信公众号
Key:4,Value:个人博客

从日志可以看出,当我们尝试重加重复Map时,并没有添加成功。

关于Map集合的详细用法,HashMap、HashTable、TreeMap的区别(这里是重点,面试可能问的比较多,这里不展开说明)

Map集合与Set集合、List集合的关系

1. Set the relationship between the set
if the key on the Map of all look together, they form a Set collection (not all key sequence can not be duplicated between the key and the key), actually Map does include a keySet()method , the user returns to the Map Set consisting of all key collection.
2. Relations with the List collection
if all the value in the Map Considered together, they are also very similar to a List: between elements and can be repeated elements, each element can find the index, but the index is not Map then use integer values, but to another object as the index.

Interface methods defined:

Map interface method

Map further comprising an inner class Entry, class encapsulates a key-value pair. Entry contains the following three methods:

Entry method

Map collection of the most typical usage is paired add, delete key-value pairs, then is to determine whether or not the Map contains the specified key, contains a specified value, may also be provided by Map keySet()Gets a collection of all the key composition method, and then use foreachAll key loop to walk through the Map, based on key can traverse all of value. The following procedure demonstrates some basic features of Map:

public class MapTest {
    public static void main(String[] args){
        Day day1 = new Day(1, 2, 3);
        Day day2 = new Day(2, 3, 4);
        Map<String,Day> map = new HashMap<String,Day>();
        //成对放入key-value对
        map.put("第一个", day1);
        map.put("第二个", day2);
        //判断是否包含指定的key
        System.out.println(map.containsKey("第一个"));
        //判断是否包含指定的value
        System.out.println(map.containsValue(day1));
        //循环遍历
        //1.获得Map中所有key组成的set集合
        Set<String> keySet = map.keySet();
        //2.使用foreach进行遍历
        for (String key : keySet) {
            //根据key获得指定的value
            System.out.println(map.get(key));
        }
        //根据key来移除key-value对
        map.remove("第一个");
        System.out.println(map);
    }
}

Output:

true
true
Day [hour=2, minute=3, second=4]
Day [hour=1, minute=2, second=3]
{第二个=Day [hour=2, minute=3, second=4]}

reference:

[Novice] how to learn Java collections

Java collection List, Set, and Map, etc. Detailed collection system (the most complete history)

Deep understanding of java collections - Collections Framework Collction, Map

Guess you like

Origin www.cnblogs.com/chenwenhao/p/12147862.html