gpt4 book ai didi

Java从ArrayList中查找数据

转载 作者:太空宇宙 更新时间:2023-11-04 13:36:32 25 4
gpt4 key购买 nike

这是我的代码的一部分,它位于两个不同的类中。现在我只想添加一个选项,当您单击查找按钮时,您可以键入雇员 ID 并显示与数组列表中的雇员 ID 匹配的雇员详细信息。

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
viewPanel("card4");
<小时/>

我该怎么做?

public class NewJFrame extends javax.swing.JFrame {
private empType type;
private List<Empoyees>objects;
private int state=0;
private DefaultListModel df;



public NewJFrame() {
try {


initComponents();
objects=new ArrayList<Empoyees>();
objects.add(new Empoyees(123, 25000f,"Mahoshadi"));
objects.add(new Empoyees(111, 95000f,"Sajani"));
objects.add(new Empoyees(253, 15000f,"Buwani"));
objects.add(new Empoyees(687, 66500f,"Thinithi"));


state=1;
viewPanel("card2");
df=new DefaultListModel();
df.addElement(objects.get(0));
df.addElement(objects.get(1));
df.addElement(objects.get(2));
df.addElement(objects.get(3));


} catch (Exception e) {
}
<小时/>
public class Empoyees {




private int empId;
private float salary;
private String empName;


public Empoyees(int empId, float salary, String empName) {
this.empId = empId;
this.salary = salary;
this.empName = empName;
}

public int getEmpId() {
return empId;
}

public float getSalary() {
return salary;
}

public String getEmpName() {
return empName;
}



@Override
public String toString() {
return "Name = " + empName + " , ID = " + empId + " , Salary = " + salary ;
}

最佳答案

不要使用List,而是使用hashmap。在这种情况下,您可以使用员工 ID 作为 HashMap 的键。并且可以使用hashmap的get(Object key)方法直接检索员工详细信息

Map<Integer,Empoyees>employeeCodeEmployeeDetailsMap=new HashMap<Integer,Empoyees>(); 

这将为您创建所需的 map 。

关于Java从ArrayList中查找数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31634929/

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