# C++中的vector和Java中的ArrayList的構造函數的區別

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"前言：之前一直存在一個理解誤區，以爲C++中的"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"存在一個構造函數可以爲"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"對象預分配空間，在調試代碼時，才發現是自己理解錯了，接收一個整數的"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"的構造函數並不是預分配空間，而是直接添加了元素，因此寫一篇文章來記錄一下。"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"C++中的vector"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"接收一個整數的"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"的構造函數實際上是直接向"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"對象中添加了元素："}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"vector arr (10);\ncout << arr.size() << endl; // 10\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果要給"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"對象預分配空間的話，必須使用"},{"type":"codeinline","content":[{"type":"text","text":"reserve()"}]},{"type":"text","text":"成員函數："}]},{"type":"codeblock","attrs":{"lang":"cpp"},"content":[{"type":"text","text":"vector arr;\narr.reserve(10);\ncout << arr.size() << endl; // 0\ncout << arr.capacity() << endl; // 10"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"Java中的ArrayList"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"而Java中的"},{"type":"codeinline","content":[{"type":"text","text":"ArrayList"}]},{"type":"text","text":"也有一個類似的構造函數，接收一個整數："}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public ArrayList(int initialCapacity)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"與C++中的"},{"type":"codeinline","content":[{"type":"text","text":"vector"}]},{"type":"text","text":"不同，該構造函數是會預分配空間的，而不是直接添加元素："}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"ArrayList arr = new ArrayList<>(10);\nSystem.out.println(arr.size()); // 0"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}