A java question. Write a class Roster that manages a LinkedList of Student objec
ID: 3828964 • Letter: A
Question
A java question. Write a class Roster that manages a LinkedList of Student objects. The Student objects are arranged alphabetically by name. You are given a Student class. Do not modify it.
The constructor for a Roster has no parameters but initializes an empty LinkedList of Students. The list is the instance variable.
Provide these methods:
1. add(Student s) adds the Student to the LinkedList. The Students are maintained in alphabetical order by name
2. remove(String name) removes the first Student with the given name
3. get Names() returns an ArrayList of Strings containing the names of all the Students
----------------------------------------------------------------------------------------------------------------------
The RosterTester and the Student are given as follow:
RosterTester.java
Student.java
Explanation / Answer
Find the below programs and output. I created the Roaster class. other two classes no change.
Roaster.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
public class Roster {
List<Student> list;
public Roster() {
list = new LinkedList<Student>();
}
public void add(Student s){
list.add(s);
Collections.sort(list, new Comparator<Student>() {
public int compare(Student node1, Student node2) {
return node1.getName().compareTo(node2.getName());
}
});
}
public void remove(String name){
//To iterate the list and check the name
for(Student s : list){
if(s.getName().equals(name)){
list.remove(s);
break;
}
}
}
public List<String> getNames(){
List<String> namesList = new ArrayList<String>();
for(Student s : list){
namesList.add(s.getName());
}
return namesList;
}
}
OUTPUT:
[]
Expected: []
[]
Expected: []
[Aman, Amy, Carlos, Predeep, Yen]
Expected: [Aman, Amy, Carlos, Predeep, Yen]
[Aman, Amy, Carlos, James, Predeep, Predeep, Yen]
Expected: [Aman, Amy, Carlos, James, Predeep, Predeep, Yen]
[Aman, Amy, Carlos, James, Predeep, Yen]
Expected: [Aman, Amy, Carlos, James, Predeep, Yen]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.