数据结构和迭代器的使用方法

Java 数据结构和迭代器使用方法

1. ArrayList (动态数组)

创建 ArrayList:

ArrayList<String> list = new ArrayList<>();

添加元素:

list.add("Element1");
list.add("Element2");

访问元素:

String element = list.get(0);

迭代器遍历:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
}

2. LinkedList (链表)

创建 LinkedList:

LinkedList<String> linkedList = new LinkedList<>();

添加元素:

linkedList.add("Element1");
linkedList.add("Element2");

访问元素:

String element = linkedList.get(0);

迭代器遍历:

Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
}

3. HashMap (哈希映射)

复制代码
HashMap<String, Integer> map = new HashMap<>();
map.put("Key1", 1);
map.put("Key2", 2);
int value = map.get("Key1");
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    String key = entry.getKey();
    int value = entry.getValue();
}
复制代码

4. HashSet (哈希集合)

HashSet<String> set = new HashSet<>();
set.add("Element1");
set.add("Element2");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
}

C++ 数据结构和迭代器使用方法

1. Vector (动态数组)

vector<int> vec;
vec.push_back(1);
vec.push_back(2);
    int element = vec[0];
for (auto it = vec.begin(); it != vec.end(); ++it) {
    int element = *it;
}

2. List (链表)

list<string> myList;
myList.push_back("Element1");
myList.push_back("Element2");
for (auto it = myList.begin(); it != myList.end(); ++it) {
    string element = *it;
}

3. Map (映射)

map<string, int> myMap;
myMap["Key1"] = 1;
myMap["Key2"] = 2;
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
    string key = it->first;
    int value = it->second;
}

4. Set (集合)

set<string> mySet;
mySet.insert("Element1");
mySet.insert("Element2");
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
    string element = *it;
}

 

posted @   周+⑦  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示