Comment rechercher et afficher un objet par numéro d'identification dans un Arraylist java?


J'ai vraiment besoin d'aide avec mon programme. Je suis nouveau sur Arraylist et je ne sais pas comment puis-je rechercher et afficher un objet par son numéro d'identification.

Le programme a donc 4 classes: Principal, Personne (classe parent) Étudiant et Employé (les deux sont enfant de Personne)

Maintenant ma classe principale a un menu qui fera le suivant:

  1. Ajouter un étudiant (l'ID doit être unique pour chaque stud )
  2. Ajouter un employé (l'ID doit être unique pour chaque pem )
  3. Recherche Étudiant ( Par ID étudiant puis l'afficher)
  4. Recherche Employé (Par employé Non puis l'afficher)
  5. Afficher tout (Afficher tous les Goujon et employé )
  6. Quitter

J'ai déjà fait cela avec la recherche et l'affichage de tableaux, mais maintenant nous devons utiliser Arraylist, ce qui est mieux mais je suis nouveau.

Toute aide et suggestion est très appréciée. Merci!!!!

Voici mon code:

Classe Principale:

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args){
        ArrayList<Student> stud = new ArrayList<Student>();
        ArrayList<Employee> emp = new ArrayList<Employee>();
        while (true) {
            int select;
            System.out.println("Menu");
            System.out.println("1. Add Student");
            System.out.println("2. Add Employee");
            System.out.println("3. Search Student");
            System.out.println("4. Search Employee");
            System.out.println("5. Display All");
            System.out.println("6. Quit");
            select = sc.nextInt();

            switch (select) {
                case 1:
                    addStud(stud);
                    break;
                case 2:
                    addEmp(emp);
                    break;
                case 3:
                    srchStud();
                    break;
                case 4:
                    srchEmp();
                case 5:
                    displayAll(stud, emp);
                    break;
                case 6:
                    return;
                default:
                    System.out.println("Invalid Option");
            }
        }
    }

    public static void addStud(ArrayList<Student> stud) {

        String name, address, course;
        int age, cNum, studNum, year;

        int addMore;
        System.out.println("ADD STUDENT");
        do {
            System.out.println("Student No: ");
            studNum = sc.nextInt();
            sc.nextLine();
            for(int x = 0; x < stud.size(); x++){ // Please help fix, this accepts another ID if already existing to prevent duplicate
                if(studNum == stud[x].getStudNum()) { // this code works with array of object but not on arraylist,
                    System.out.println("The Student ID: " +studNum+ " already exist.\nEnter New Student ID: ");
                    studNum = sc.nextInt();
                    sc.nextLine();
                    x = -1;
                }
            }
            System.out.println("Name: ");
            name = sc.nextLine();
            System.out.println("Age: ");
            age = sc.nextInt();
            sc.nextLine();
            System.out.println("Address: ");
            address = sc.nextLine();
            System.out.println("Contact No: ");
            cNum = sc.nextInt();
            sc.nextLine();
            System.out.println("Course: ");
            course = sc.nextLine();
            System.out.println("Year: ");
            year = sc.nextInt();
            sc.nextLine();

            stud.add(new Student(name, address, age, cNum, studNum, year, course));

            System.out.println("To add another Student Record Press 1 [any] number to stop");
            addMore = sc.nextInt();
            sc.nextLine();
        } while (addMore == 1);

    }

    public static void addEmp(ArrayList<Employee> emp) {

         String name, address, position;
         int age, cNum, empNum;
         double salary;

        int addMore;
        System.out.println("ADD Employee");
        do {
            System.out.println("Employee No: ");
            empNum = sc.nextInt();
            sc.nextLine();
            for(int x = 0; x < emp.size(); x++){
                if(empNum == emp[x].getEmpNum()) {
                    System.out.println("The Employee ID: " +empNum+ " already exist.\nEnter New Student ID: ");
                    empNum = sc.nextInt();
                    sc.nextLine();
                    x = -1;
                }
            }
            System.out.println("Name: ");
            name = sc.nextLine();
            System.out.println("Age: ");
            age = sc.nextInt();
            sc.nextLine();
            System.out.println("Address: ");
            address = sc.nextLine();
            System.out.println("Contact No: ");
            cNum = sc.nextInt();
            sc.nextLine();
            System.out.println("Position: ");
            position = sc.nextLine();
            System.out.println("Salary: ");
            salary = sc.nextInt();
            sc.nextLine();

            emp.add(new Employee(name, address, age, cNum, empNum, salary, position));

            System.out.println("To add another Student Record Press 1 [any] number to stop");
            addMore = sc.nextInt();
            sc.nextLine();
        } while (addMore == 1);

    }

    public static void displayAll(ArrayList<Student> stud, ArrayList<Employee> emp){ // Definitely not working with Arraylist
        System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
        for (int x = 0; x < stud.size(); x++) {

            System.out.println(stud[x].getStudNum() + "\t\t\t\t" + stud[x].getName() + "\t\t\t\t" + stud[x].getCourse() + "\t\t\t\t" + stud[x].getYear());

        }
    }      
}

Classe de Personne :

public class Person {

    private String name, address;
    private int age, cNum;

    public Person() {
    }

    public Person(String name, String address, int age, int cNum) {
        this.name = name;
        this.address = address;
        this.age = age;
        this.cNum = cNum;
    }

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getcNum() {
        return cNum;
    }

    public void setcNum(int cNum) {
        this.cNum = cNum;
    }
}

Classe d'étudiant:

public class Student extends Person{

    private int studNum, year;
    private String course;

    public Student(String name, String address, int age, int cNum, int studNum, int year, String course) {
        super(name, address, age, cNum);
        this.studNum = studNum;
        this.year = year;
        this.course = course;
    }

    public int getStudNum() {
        return studNum;
    }

    public void setStudNum(int studNum) {
        this.studNum = studNum;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }
}

Classe D'Employés :

public class Employee extends Person {

    private int empNum;
    private double salary;
    private String position;

    public Employee(String name, String address, int age, int cNum, int empNum, double salary, String position) {
        super(name, address, age, cNum);
        this.empNum = empNum;
        this.salary = salary;
        this.position = position;
    }

    public int getEmpNum() {
        return empNum;
    }

    public void setEmpNum(int empNum) {
        this.empNum = empNum;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }
}
Author: Trushit Shekhda, 2020-01-20

2 answers

Si vous n'êtes pas limité à utiliser ArrayList, de meilleures performances seront obtenues en utilisant une carte.

Map<Integer, Employee>  employeeIndex = new HashMap<>();
    //put
    employeeIndex.put(employeeId, empployee);
    //get
    employeeIndex.get(employeeId);

Au cas où vous auriez besoin d'utiliser ArrayList, vous pouvez utiliser filter:

List<Student> students = new ArrayList<Student>();

        List<Student> filteredStudent = students.stream()
            .filter(student -> student.getStudNum() == student_id)
            .collect(Collectors.toList());
 1
Author: Shafiul, 2020-01-21 09:47:56

Juste de cette façon si vous recherchez un étudiant, l'id est 12

ArrayList<Integer> students;
students.forEach(stu -> {if ( stu.getStudNum() == 2) System.out.println(stu.getName());});
 0
Author: kevin ternet, 2020-01-20 16:42:05