gpt4 book ai didi

java - 在 Java 中创建示例时可以使用 "linked list"吗?

转载 作者:行者123 更新时间:2023-12-02 09:20:45 25 4
gpt4 key购买 nike

创建实例时可以使用链表吗?

示例:

我有 Main 类和一个 Employee 类。

主类:

 Employee a1 = new Employee();

当我们创建Instance时,通常会这样写代码。

但是我想知道是否有任何方法可以使用链表创建实例。

像这样:

LinkedList<String> alist = new LinkedList<String>();  
Employee alist(index) = new Employee();

最佳答案

您已经创建了 List<String> ,它不能容纳 Employee 的实例,但也许他们的名字......

您似乎想要这样的东西:

Employee employee = new Employee();
// maybe set some attributes (the next line is a guess due to a lack of information)
employee.setName("E. M. Ployee");

// create a list of employees
List<Employee> employees = new LinkedList<>();
// and add the employee
employees.add(employee);

如果您有 List<String>和一个 class Employee看起来和这个很相似

class Employee {

private String name;

public Employee(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

然后你可以创建 Employee 的实例对于名称列表中的每个名称:

public static void main(String[] args) {
// create a list of names (String)
List<String> names = new LinkedList<>();
names.add("E. M. Ployee");
names.add("U. R. Fired");
// create a list of employees (Employee)
List<Employee> employees = new LinkedList<>();
// go through the names and create an Employee for each one
names.forEach(name -> employees.add(new Employee(name)));
// then print the names from the employee objects that are in the list of employees
employees.forEach(employee -> System.out.println(employee.getName()));
}

关于java - 在 Java 中创建示例时可以使用 "linked list"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58707530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com