LinkedHashMap转对象
时间: 2023-05-27 16:05:08 浏览: 58
LinkedHashMap is a data structure used to store key-value pairs in the order they were inserted. To convert a LinkedHashMap to an object, you can do the following:
1. Create a class that matches the structure of the LinkedHashMap. This class should have fields that correspond to the keys in the LinkedHashMap.
2. Loop through the LinkedHashMap and set the values of the fields in the object using the values in the LinkedHashMap.
Here's an example:
```
import java.util.LinkedHashMap;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
map.put("name", "John");
map.put("age", 30);
Person person = new Person((String) map.get("name"), (int) map.get("age"));
System.out.println(person.getName() + " " + person.getAge());
}
}
```
In this example, we have a Person class with name and age fields. We create a LinkedHashMap with keys "name" and "age" and values "John" and 30, respectively. We then create a Person object and set its name and age fields using the values in the LinkedHashMap. Finally, we print out the name and age of the Person object.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)