1.创建Human类,包括name属性,重写toString方法。 2.生成多个Human对象,加入到List和Set中 3.定义遍历方法,调用方法遍历LIst和set,观察结果。 4.在List的第1个索引处加入一个新的Human对象,遍历List,
时间: 2023-06-01 09:06:08 浏览: 59
请问您想让我如何回答这个问题?
如果您需要我以编程语言的方式回答这个问题,我可以为您提供Java代码如下:
public class Human {
private String name;
public Human(String name) {
this.name = name;
}
@Override
public String toString() {
return "Human{" +
"name='" + name + '\'' +
'}';
}
}
public class Main {
public static void main(String[] args) {
//生成多个Human对象
Human h1 = new Human("Tom");
Human h2 = new Human("Jerry");
Human h3 = new Human("Mike");
//加入到List中
List<Human> list = new ArrayList<>();
list.add(h1);
list.add(h2);
list.add(h3);
//加入到Set中
Set<Human> set = new HashSet<>();
set.add(h1);
set.add(h2);
set.add(h3);
//遍历List
System.out.println("List遍历结果:");
for (Human h : list) {
System.out.println(h.toString());
}
//在List的第1个索引处加入一个新的Human对象
Human h4 = new Human("Lucy");
list.add(0, h4);
//遍历List
System.out.println("List遍历结果(加入新对象后):");
for (Human h : list) {
System.out.println(h.toString());
}
//遍历Set
System.out.println("Set遍历结果:");
for (Human h : set) {
System.out.println(h.toString());
}
}
}
如果您有其他问题需要我回答,请随时告诉我。