gpt4 book ai didi

java - 如何查看对象列表以查找匹配项?

转载 作者:行者123 更新时间:2023-12-01 09:33:59 24 4
gpt4 key购买 nike

我正在尝试比较一堆同一类的对象来搜索匹配的 ID?这是 GroupClass,当输入新条目时,它将根据 idNumber 进行测试以查看是否存在匹配。

Public GroupClass {

private int idNumber;
private String name;
private double income;


public GroupClass(int id, String name, double income){
this.idNumber = id;
this.name = name;
this.income = income;
}

public int getIdNumber() {
return idNumber;
}

public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}

public String getName() {
return name;
}

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

public double getIncome() {
return income;
}

public void setIncome(double income) {
this.income = income;
}
}

这是主要方法

import static java.lang.reflect.Array.set;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;


public class ListTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

Set<GroupClass> groupArray = new LinkedHashSet<>();
System.out.println("Enter a ID Number");
int id = input.nextInt();
System.out.println("Enter a First Name");
String name = input.next();
System.out.println("Enter a an Income");
double income = input.nextDouble();


groupArray.add(new GroupClass(1111, "Billy", 178000));
groupArray.add(new GroupClass(1112, "Sam", 78000));
groupArray.add(new GroupClass(1113, "Mark", 79000));

groupArray.add(new GroupClass(id, name, income));
printTheClass(groupArray);


}

public static void printTheClass(Set group){
for(Object theArray: group){
System.out.println(theArray + " ");
}
}

}

我见过一些类似的问题,但无法让它适用于我的特定情况,提前致谢。

最佳答案

根据上面的评论,您重写了 equals 方法,但这可能不适合该类的长期增长。

但是使用您现有的代码尝试

public static void printTheClass(Set<GroupClass> group){
for(GroupClass theArray: group){
System.out.println(theArray + " ");
}
}

public static GroupClass findTheClass(Set<GroupClass> group, int id){
for(GroupClass obj: group){
if(obj.getIdNumber == id) return obj;
}
return null;
}

这可以用作

if (findTheClass (groupArray, id) == null) {
groupArray.add (new GroupClass(id, name, income));
}

关于java - 如何查看对象列表以查找匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39159732/

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