简体   繁体   English

在Java中检查对象是否在arraylist中

[英]Checking if an object is in arraylist in Java

So here is assignment :所以这里是分配:
A student entity has a name and an address (both represented by an object of class Name and Address ), in addition to a university ID , and a course schedule represented by an ArrayList of Courses学生实体除了大学 ID 外,还有姓名和地址(均由NameAddress的对象表示),以及由 ArrayList of Courses 表示的课程表

  • Your code should not allow the creation of Two students with the same university ID您的代码不应允许创建两个具有相同大学 ID 的学生

So I'm thinking of using ArrayList to hold a list of student and check if student exists or not before create a new student.所以我正在考虑使用 ArrayList 来保存学生列表并在创建新学生之前检查学生是否存在。 sorry, this is my first question so I'm trying my best to explain it:抱歉,这是我的第一个问题,所以我正在尽力解释:

This is my Address class:这是我的地址类:

public class Address {
private int streetNumber;
private String streetName;
private String city;
private String state;
private int province;
private String country;

public Address (int streetNumber,String streetName,String city,String state,int province,String country)
{
    this.streetNumber=streetNumber;
    this.streetName=streetName;
    this.city=city;
    this.state=state;
    this.province=province;
    this.country=country;
}
public int getStreetNumber() {
    return streetNumber;
}

public void setStreetNumber(int streetNumber) {
    this.streetNumber = streetNumber;
}

public String getStreetName() {
    return streetName;
}

public void setStreetName(String streetName) {
    this.streetName = streetName;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public String getState() {
    return state;
}

public void setState(String state) {
    this.state = state;
}

public int getProvince() {
    return province;
}

public void setProvince(int province) {
    this.province = province;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String toString() {
    return " [streetNumber=" + streetNumber + ", streetName=" + streetName
            + ", city=" + city + ", state=" + state + ", province="+province+", country="
            + country + "]";
}

public boolean equals(Address add)
{
    if(add==null)
    {
        return true;
    }
    if(this.getClass()!=add.getClass())
    {
        return false;
    }
    Address address=(Address) add;
    return streetNumber==address.streetNumber && 
            province==address.province && streetName.equals(address.streetName)
            && city.equals(address.city)&& state.equals(address.state)&& country.equals(address.country);
}

} }

This is my Name class这是我的名字类

public class Name {
private String firstName;
private String lastName;
private char middle;

public Name (String fiName,String laName, char middle)
{       
    this.firstName=fiName;
    this.lastName=laName;
    this.middle=middle;

}

public String getFirst()
{
    return firstName;
}

public void setFirst(String first)
{
    firstName=first;
}
public String getLast()
{
    return lastName;
}

public void setLast(String last)
{
    lastName=last;
}
public char getMiddle()
{
    return middle;
}
public void setMiddle(char midd)
{
    middle=midd;
}
/*public String toString()
{
     return "[First Name= "+ firstName +" Last Name "+ lastName+" Middle Name "+ middle +"";
}*/

} }

This is my Student class:这是我的学生类:

public class Student {
private int studentId;
private Name name;
private Address address;
boolean a;
ArrayList<Course> courseSchedule = new ArrayList<Course>();
ArrayList<Student> student=new ArrayList<Student>();

public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
    if(student.contains(id))
    {
        System.out.println("Student cannot be same id");
    }
    else
    {
        address= new Address(stNumber,stName,city,state,province,country);
        name=new Name(fiName,laName,middle);    
        this.studentId=id;
        student.add();
    }

}

public int getID() 
{
    return studentId;
}
public void setId(int id) 
{
    this.studentId = id;
}
public ArrayList<Course> getCourseSchedule() 
{
    return courseSchedule;
}
public void setCourseSchedule(ArrayList<Course> courseSchedule) 
{
    this.courseSchedule = courseSchedule;
}
 public void addCourse(Course c) {
       courseSchedule.add(c);
 }
 public void dropCourse(Course course) {
       courseSchedule.remove(course);
 }

} }

My question is how can you add Student Object into Student ArrayList and how can I check if the Student Id exists in ArrayList with contains() method我的问题是如何将 Student 对象添加到 Student ArrayList 中,以及如何使用 contains() 方法检查 ArrayList 中是否存在 Student Id

student.contains(id) this line right here it does not seem to be right I hope im explain my question a little clear now. student.contains(id)这行就在这里,它似乎不对,我希望我现在解释一下我的问题。 Sorry for my english also.也对不起我的英语。

You would not keep a list of Student objects within the class for Student . 你不会保留名单Student在类内的对象Student Your ArrayList<Student> student=new ArrayList<Student>(); 您的ArrayList<Student> student=new ArrayList<Student>(); does not belong there. 不属于那里。

You would have another structure or collection kept elsewhere named something like StudentBody . 您将拥有另一个结构或集合,该结构或集合保存在其他地方,命名为StudentBody When a student is instantiated, it is added to the StudentBody collection. 实例化学生后,会将其添加到StudentBody集合。

List< Student > studentBody = new ArrayList< Student >() ;  // This list is stored somewhere else in your app.

You could loop a List of Student objects in the StudentBody object. 您可以在StudentBody对象中循环一个Student对象List For each you would access the UniversityId member field and compare to your new one being added. 对于每一个,您将访问UniversityId成员字段并将其与要添加的新成员进行比较。

Or you could use a Map , where the key is a UniversityId object and the value is a Student object. 或者,您可以使用Map ,其中UniversityId对象,而值是Student对象。 Check for an existing key before adding. 添加前检查现有密钥。

These solutions ignore the important issue of concurrency . 这些解决方案忽略了并发这一重要问题。 But that is likely okay for a homework assignment in a beginning course in programming. 但这对于编程入门课程中的家庭作业来说可能还可以。

Use A HashMap() for collecting information based on unique Ids. 使用HashMap()基于唯一ID收集信息。

public class Student {
private int studentId;
private Name name;
private Address address;
private static HashMap<Integer,Student> students = new ConcurrentHashMap<>(); // Make a static Map so all objectrs shared same data

public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
    if(students.contains(id))
    {
        System.out.println("Student can be same id");
    }
    else
    {
        address= new Address(stNumber,stName,city,state,province,country);
        name=new Name(fiName,laName,middle);    
        this.studentId=id;
        students.put(id,this);  // use this to add current object
    }

}

By reading the ArrayList Source code, You should override the student class's euqals function. 通过阅读ArrayList源代码,您应该覆盖学生类的euqals函数。

public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }    
public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                 if (elementData[i]==null)
                     return i;
                 } else {
                    for (int i = 0; i < size; i++)
                        if (o.equals(elementData[i]))
                            return i;
        }
     return -1;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM