在Java中实现关联数组
关联数组以(键,值)对的形式存储元素集。关联数组是唯一键和值的集合,其中每个键与一个值相关联。
关联数组是一种抽象数据类型,如由(键,值)对组成的映射,这样每个键值在集合中最多出现一次。基本上,具有命名索引的数组称为关联数组或哈希。
在Java中,很难形成关联数组,但是使用HashMap可以轻松实现:
句法:
Map map = new HashMap();
// method to add the key,value pair in hashmap
map.put("geeks", "course");
map.put("name", "geeks");
// method to get the value
map.get("name"); // returns "geeks"
使用 Map函数实现关联数组或关联列表数组的步骤:
1.首先初始化地图
Map map = new HashMap<>();
2.然后使用put方法将Key,Value放入地图
map.put("geeks","Course");
3.将所有Key Value放入map后使用entrySet()方法将map转换为set
Set > set = map.entrySet();
4.然后现在使用函数将集合转换为列表数组;
List> list=new ArrayList<>(set);
关联数组的实现:
Java
// Java program to implement the associate array
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Forming the map
Map map = new HashMap<>();
// method to store the value and
// key into the map
map.put("name", "rohit");
map.put("geeks", "course");
map.put("India Capital", "Delhi");
System.out.println(map.size());
Set > set
= map.entrySet();
List > list
= new ArrayList<>(set);
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i).getKey() + ": "
+ list.get(i).getValue());
}
}
}
Java
// Java program to implement the associate array
// and iterate it using iterator() method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Forming the map
Map map = new HashMap<>();
// method to store the put the value and
// key into the map
map.put("Roll no", 45);
map.put("Total Question", 113);
map.put("Marks ", 400);
// method to access the value based on
// the key
System.out.println(map.size());
Set > set
= map.entrySet();
List > list
= new ArrayList<>(set);
// using the iterator
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
输出
3
India Capital: Delhi
geeks: course
name: rohit
- 时间复杂度: O(n)
- 空间复杂度: O(n)
我们可以使用iterator()方法遍历数组
句法:
Iterator it = map.entrySet().iterator();
Java
// Java program to implement the associate array
// and iterate it using iterator() method
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Forming the map
Map map = new HashMap<>();
// method to store the put the value and
// key into the map
map.put("Roll no", 45);
map.put("Total Question", 113);
map.put("Marks ", 400);
// method to access the value based on
// the key
System.out.println(map.size());
Set > set
= map.entrySet();
List > list
= new ArrayList<>(set);
// using the iterator
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
输出
3
Total Question=113
Roll no=45
Marks =400
- 时间复杂度: O(n)
- 空间复杂度: O(n)