简体   繁体   中英

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

  • Your code should not allow the creation of Two students with the same university 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. 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.contains(id) this line right here it does not seem to be right I hope im explain my question a little clear now. Sorry for my english also.

You would not keep a list of Student objects within the class for Student . Your ArrayList<Student> student=new ArrayList<Student>(); does not belong there.

You would have another structure or collection kept elsewhere named something like StudentBody . When a student is instantiated, it is added to the StudentBody collection.

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. For each you would access the UniversityId member field and compare to your new one being added.

Or you could use a Map , where the key is a UniversityId object and the value is a Student object. 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.

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.

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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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