avaHashMap重写 Student 类的 toString() 方法。 java.util.*重写fanfaStudent编写学生类,有姓名,年龄,性别三种属性。 编写测试类,创建学号id,为下列三名学生进行配对,并输出配对后的键值对: [a,18,男]
时间: 2024-03-06 09:50:56 浏览: 39
好的,我先来回答你的第一个问题。是的,我后面提到的ChitGPT是一个基于GPT-2的类Chatbot的AI,它是由CSDN开发的,与OpenAI的ChatGPT没有关系。
至于你的第二个问题,我可以帮你写出如下的代码:
```java
import java.util.HashMap;
public class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// 重写 toString() 方法
@Override
public String toString() {
return "[" + name + "," + age + "," + gender + "]";
}
public static void main(String[] args) {
HashMap<String, Student> pairs = new HashMap<>();
Student stu1 = new Student("a", 18, "男");
Student stu2 = new Student("b", 19, "女");
Student stu3 = new Student("c", 20, "男");
pairs.put("a", stu1);
pairs.put("b", stu2);
pairs.put("c", stu3);
System.out.println(pairs);
}
}
```
在这段代码中,我们首先定义了一个`Student`类,它有三个属性:姓名、年龄和性别。我们重写了`toString()`方法,让它返回一个格式化的字符串,方便我们输出键值对。
然后我们在`main()`方法中创建了三个`Student`对象,并将它们和学号id一起放入`HashMap`中。最后,我们输出整个`HashMap`,就可以得到配对后的键值对了。
相关推荐
![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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)