Question

what is the solution for this Java problem?

Generics Suppose you need to process the following information regarding Students and Courses: A Student has a name, age, ID,

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Question 1 : (UML diagram)

- 0 X StarUML (UNREGISTERED) File Edit Format Model Tools View Window Debug Help Working Diagrams Model Explorer Q. Main - Mo

In the UML diagram, we will not show the extra generic class ArrayList and the class which contains main(). ArrayList class is already predefined in java but for a clearer understanding, i have written it alongwith the code.

Question 2 :

CODE (with screen shot) :

import java.util.*;
//Generic class for ArrayList
class ArrayList<E> {
List<E> arr;
public ArrayList() {
arr=new java.util.ArrayList<>();
}
public void add(E e) {
arr.add(e);
}
public void remove(E e) {
arr.remove(e);
}
public int size() {
return arr.size();
}
public boolean contains(E e) {
return arr.contains(e);
}

public E get(int i) {
return arr.get(i);
}
}
class Student {
private String name;
private int age;
private String id;
private ArrayList<Course> courseList;
//Generic type ArrayList is used
//Constructor
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
courseList=new ArrayList<>(); //Instantiate the list
}
//setter and getter methods for each private variable
public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setId(String id) {
this.id = id;
}

public String getId() {
return id;
}
public boolean addCourse(Course course) { //method to add a course to student's course list
if(courseList.contains(course) || courseList.size()==6) {
return false; //Do not add the course if courseList already has the course or it has max 6 courses
} //Otherwise do the following
courseList.add(course); //add course in the courseList
course.addStudent(this); //Also update the studentList for this particular course
return true;
}
public boolean removeCourse(Course course) { //method to remove the course a course from the student course list
if(!courseList.contains(course)) {
return false;
}
courseList.remove(course);
course.removeStudent(this);
return true;
}
public String printSchedule() { //Printing the courses and student informations
String s="";
for(int i=0;i<courseList.size();i++) {
s=s+", "+courseList.get(i).getName();
}
return "\nName : "+name+"\nAge : "+age+"\nID : "+id+"\nCourses : ["+s.substring(1)+" ]";
}
}
class Course {
private String name;
private ArrayList<Student> studentList;
//Constructor for course class which takes as input the name
public Course(String name) {
this.name = name;
studentList = new ArrayList<>();
}
//setter and getter method for the name of course
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
//Adding student to the course
boolean addStudent(Student student) {
if(studentList.contains(student) || studentList.size()==30) {
return false;
}
studentList.add(student);
student.addCourse(this);
return true;
}
//Removing student from the course
boolean removeStudent(Student student) {
if(!studentList.contains(student)) {
return false;
}
studentList.remove(student);
student.removeCourse(this);
return true;
}
//Prints the student list of each course
String printStudents() {
String s="";
for(int i=0;i<studentList.size();i++) {
s=s+", "+studentList.get(i).getName();
}
return "\nNumber of Students attending "+name+" : "+studentList.size()+"\nNames ["+s.substring(1)+" ]";
}
}
class TestStudent { //Tester class as mentioned in the question
public static void main(String[] args) {
Student s1=new Student("John Marcus",24,"S101");
Student s2=new Student("Alina Gilbert",20,"S102");
Student s3=new Student("Henry Roberts",25,"S103");
Student s4=new Student("Jacob Meyer",22,"S104");
Student s5=new Student("Jeremy Dulcet",23,"S105");
Course c1=new Course("Artificial Intelligence");
Course c2=new Course("Image Processing");
Course c3=new Course("Core Java");
s1.addCourse(c1);
s1.addCourse(c2);
s2.addCourse(c3);
s2.addCourse(c2);
s3.addCourse(c3);
s3.addCourse(c3); //Adding c3 to s3 twice, so this will return false because c3 has already been added to student s3
s3.addCourse(c1);
s4.addCourse(c2);
s4.addCourse(c3);
s5.addCourse(c1);
s5.addCourse(c2);
System.out.println(s1.printSchedule());
System.out.println(s2.printSchedule());
System.out.println(s3.printSchedule());
System.out.println(s4.printSchedule());
System.out.println(s5.printSchedule());
System.out.println(c1.printStudents());
System.out.println(c2.printStudents());
System.out.println(c3.printStudents());
}
  
}

_ JavaApplication 1 - NetBeans IDE 8.2 RC File Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Help <d

_ 0 X JavaApplication1 - NetBeans IDE 8.2 RC File Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Help

_ 0 X JavaApplication 1 - NetBeans IDE 8.2 RC File Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Hel

_ 0 X JavaApplication 1 - NetBeans IDE 8.2 RC File Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Hel

_ 0 X JavaApplication 1 - NetBeans IDE 8.2 RC File Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Hel

OUTPUT :

_ JavaApplication 1 - NetBeans IDE 8.2 RC File Edit View Navigate Source Refactor Run Debug Profile Team Tools Window Help <d

Question 3 :

The ArrayList generic type is better than arrays because it saves us a lot of trouble to find out any value or information. It is easier to add and remove any object or value from the arrayList without having to iterate everytime to that index location :

Example consider the code :

boolean addStudent(Student student) {
if(studentList.contains(student) || studentList.size()==30) {
return false;
}
studentList.add(student);
student.addCourse(this);
return true;
}
//Removing student from the course
boolean removeStudent(Student student) {
if(!studentList.contains(student)) {
return false;
}
studentList.remove(student);
student.removeCourse(this);
return true;
}

In this code, we can add and remove data from 'studentList' with just one line of code without any iterations or worrying about its size.

Had it been an array the a for loop would have to be run from 0 upto the last index where value is stored and then it would have been possible to add the object.

Hence we would need to maintain another variable which is size of array, which is not needed in the arrayList.

Also when removing from an array, each time the size of array would have to be reduced. But becuase we are using arrayList, so these mechanisms are automatically done and we need not worry about it.

Question 4 :

Generic instantiation is to decide the type of the class at runtime. It can be any kind of Object but we do not know about it before hand.

Generics helps us in code reusability

For example :

class Stack<E> {

}

This is a generic class of stack. Now we can use this class to create a stack of integers, string values or any other object values and define them at runtime as per convenience inside the main method. This is the advantage of using generics.

Instantiation would be like :

Stack<String> s = new Stack<>();

Example from the code :

class Student {
private String name;
private int age;
private String id;
private ArrayList<Course> courseList;
//Generic type ArrayList is used
//Constructor
public Student(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
courseList=new ArrayList<>(); //Instantiate the list
}

Just look at the consturctor of Student class. we have initialized the ArrayList has type Course which is another class.

This ArrayList is a generic type class itself which can be of any type. In Student class it is of Course type and in Course class it is of Student type.

Add a comment
Know the answer?
Add Answer to:
what is the solution for this Java problem? Generics Suppose you need to process the following...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Writing 3 Java Classes for Student registration /** * A class which maintains basic information about...

    Writing 3 Java Classes for Student registration /** * A class which maintains basic information about an academic course. */ public class Course {    /** * Attributes. */ private String code; private String title; private String dept; // name of department offering the course private int credits; /** * Constructor. */ public Course(String code, String title, int credits) { // TODO : initialize instance variables, use the static method defined in // Registrar to initialize the dept name variable...

  • You are asked to build and test the following system using Java and the object-oriented concepts ...

    You are asked to build and test the following system using Java and the object-oriented concepts you learned in this course: Project (20 marks) CIT College of Information technology has students, faculty, courses and departments. You are asked to create a program to manage all these information's. Create a class CIT to represents the following: Array of Students, each student is represented by class Student. Array of Faculty, each faculty is represented by class Faculty. Array of Course, each course...

  • How to complete this methods: import java.io.FileInputStream; import java.io.FileNotFoundException; import java.time.Loc...

    How to complete this methods: import java.io.FileInputStream; import java.io.FileNotFoundException; import java.time.LocalDate; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; /** * Utility class that deals with all the other classes. * * @author EECS2030 Summer 2019 * */ public final class Registrar {    public static final String COURSES_FILE = "Courses.csv";    public static final String STUDENTS_FILE = "Students.csv";    public static final String PATH = System.getProperty("java.class.path");    /**    * Hash table to store the list of students using their...

  • Student class: Instance variables name id Constructors: Default constructor Constructor that has id and name passed...

    Student class: Instance variables name id Constructors: Default constructor Constructor that has id and name passed to the constructor Methods: Accessors int getID( ) String getName( ) Class Roster: This class will implement the functionality of all roster for school. Instance Variables a final int MAX_NUM representing the maximum number of students allowed on the roster an ArrayList storing students Constructors a default constructor should initialize the list to empty strings a single parameter constructor that takes an ArrayList<Student> Both...

  • Using Python. 3) Create a single-linked list (StudentList) where the data in the link is an object of type pointer to Student as defined below. Note that you need to store and pass a pointer of type...

    Using Python. 3) Create a single-linked list (StudentList) where the data in the link is an object of type pointer to Student as defined below. Note that you need to store and pass a pointer of type Student so that you do not create duplicate objects. Test your list with the provided program. You will find example code for a single-linked list of integers in Moodle that you can base your solution on. For your find methods, you can either...

  • Complete the following Java class. In this class, inside the main() method, user first enters the...

    Complete the following Java class. In this class, inside the main() method, user first enters the name of the students in a while loop. Then, in an enhanced for loop, and by using the method getScores(), user enters the grades of each student. Finally, the list of the students and their final scores will be printed out using a for loop. Using the comments provided, complete the code in methods finalScore(), minimum(), and sum(). import java.util.Scanner; import java.util.ArrayList; public class...

  • I need some help fixing this error. I completed the code, just modify it so the...

    I need some help fixing this error. I completed the code, just modify it so the error is gone. I had to remove the imports and parts of the test to fit everything public class Scheduler {    private List listOfCourses;    private List listOfStudents;    public Scheduler() {    listOfCourses = new ArrayList();    listOfStudents = new ArrayList();    }    public void addCourse(Course course) {    listOfCourses.add(course);    }    public List getCourses() {    List courseList =...

  • java A University would like to implement its students registery as a binary search tree, calledStudentBST....

    java A University would like to implement its students registery as a binary search tree, calledStudentBST. Write an Student node class, called StudentNode, to hold the following information about an Student: - id (as a int) - gpa (as double) StudentNode should have constructors and methods (getters, setters, and toString()) to manage Write the StudentBST class, which is a binary search tree to hold objects of the class StudentNode. The key in each node is the id. : import.java.ArrayList; public...

  • DO NOT COPY AND PASTED!!!!!!!!!!!!! IF YOU DO NOT HOW TO DO IT, JUST DO NOT...

    DO NOT COPY AND PASTED!!!!!!!!!!!!! IF YOU DO NOT HOW TO DO IT, JUST DO NOT ANSWER MY QUESTIONS package scheduler; import java.util.List; public class Scheduler { /** * Instantiates a new, empty scheduler. */ public Scheduler() { } /** * Adds a course to the scheduler. * * @param course the course to be added */ public void addCourse(Course course) { } /** * Returns the list of courses that this scheduler knows about. * * This returned object...

  • In Java programming language Please write code for the 6 methods below: Assume that Student class...

    In Java programming language Please write code for the 6 methods below: Assume that Student class has name, age, gpa, and major, constructor to initialize all data, method toString() to return string reresentation of student objects, getter methods to get age, major, and gpa, setter method to set age to given input, and method isHonors that returns boolean value true for honors students and false otherwise. 1) Write a method that accepts an array of student objects, and n, the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT