I have to use a HashSet where a lot of duplicate value may be inserted. But I want to preserve the earlier data inserted in the hash when a later insertion makes the duplicate. To examine this I have write the following code and insert many duplicate value, but it doesn't satisfy me. Please see the code below -
import java.util.HashSet;
import java.util.Set;
public class SetTest {
private static Set<Student> studentSet = new HashSet<Student>();
private static Student s1, s2, s3, s4, s5, s6, s7, s8, s9;
public static void main(String args[]){
s1 = new Student(1, 1, "Syeful", "first boy");
s2 = new Student(2, 2, "Razib", "no comments");
s3 = new Student(3, 3, "Bulbul", "should remain");
s4 = new Student(4, 3, "Bulbul", "should not remain");
s5 = new Student(5, 4, "Bulbul", "should remain");
s9 = new Student(9, 5, "Proshanto", "kaka - my favourite");
studentSet.add(s1);
studentSet.add(s2);
studentSet.add(s3);
studentSet.add(s4);
studentSet.add(s5);
studentSet.add(s9);
for(Student each : studentSet){
System.out.println("SrNo: " +each.getSrNo()+ " roleNo: "
+each.getRoleNo()+ " name: " +each.getName()+
" coment: " +each.getComment());
}
}
}
class Student{
private int srNo;
private int roleNo;
private String name;
private String comment;
public Student(int srNo, int role, String name, String comment) {
super();
this.srNo = srNo;
this.roleNo = role;
this.name = name;
this.comment = comment;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + roleNo;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (roleNo != other.roleNo) {
return false;
}
return true;
}
public int getSrNo() {
return srNo;
}
public int getRoleNo() {
return roleNo;
}
public String getName() {
return name;
}
public String getComment() {
return comment;
}
}
And the output is:
Set Size: 5
SrNo: 9 roleNo: 5 name: Proshanto coment: kaka - my favourite
SrNo: 2 roleNo: 2 name: Razib coment: no comments
SrNo: 1 roleNo: 1 name: Syeful coment: first boy
SrNo: 5 roleNo: 4 name: Bulbul coment: should remain
SrNo: 3 roleNo: 3 name: Bulbul coment: should remain
It seems me to clarify some points before asking the questions so that I can explain it properly and clarify my understanding as well.
I want to maintain the uniqueness of 'Student' based on roleNo and name.That's why the hashCode() and equals() role is made up with these property. So according to this implementation s3 and s4 are duplicate of each other even thought the comment , srNo property of them differs from each other.
HashSet is unordered.
When s4 is added in the set, we can see from the out put that s4 is discarded from the set and s3 remains.
Suppose I want to add another object of student s100 = new Student(3, 3, "Bulbul", "earlier instance suppressed"); which is the duplicate of s3. Let we have inserted a lot of duplicate of s3 before inserting s100.
Question:
Since set is unsorted and the duplicate dose not exist in set, is there any possibility that the s3 is removed by s100? I want to persist the earlier object discarding the later one. The small amount of data is not clarifying the fact. I think in this case a sorted Set may used. But does the HashSet can serve the purpose?
Thanks in advance.
HashSet.add(E e) leaves the set unchanged if it already contains the specified element. So, there are no circumstances where s3 would be removed by s100.
If you do not want collisions in your set, you need to redefine your hashing function to include more data in it, such as getSrNo. Relational Databases traditionally perform this using a unique primary key which is automatically generated for every new entry. This of "StudentID" or something like that, which should be unique across the school.
Related
I have two classes, one named Bird the other Runtime. The bird class creates birds - name, latin name. The Runtime class has 4 methods, only one is important for this question, that is the 'add' method. The add method when called upon needs to take input from the user that is name and latin name, these are saved into a string variable 'name' and 'latin name' and I call the Bird class constructor and pass in these string variables into its parameter and finally it is added to an ArrayList. However I get duplicate values, if I were to write the same bird twice.
I have tried to convert the ArrayList into a set and convert it back again into an ArrayList, i did this within the add method, this did not work. I suspect it is down to my poor understanding of how objects are stored in an ArrayList. I also created a getName method within the Bird class, so I can use list.get(i).getName, and if the name is equal to the one typed by the user, it prompts the user accordingly, if not it is added to my ArrayList. This also did not work. I also tried a for loop that would go through the ArrayList and an if statement would determine if the name typed by the user exists within the ArrayList, this also did not work, the attempt was early on so I can't remember exactly the error message, but the add method is called from within a while loop, and I think the error message was concurrent modification, I'm not entirely sure so please ignore that, my point is showing the various solutions I tried.
Below is The Bird class
public class Bird{
int obeservation = 0;
String name;
String latinName;
public Bird(String name, String latinName){
this.name = name;
this.latinName = latinName;
}
public void addBird(String name, String latinName){
this.name = name;
this.latinName = latinName;
}
public String getName(){
return this.name;
}
public String statistics(){
return this.name + " (" + this.latinName + ") : " +
this.obeservation + " observation";
}
}
Below is the Runtime class
public class Runtime {
ArrayList<Bird> birds = new ArrayList<Bird>();
Scanner scan = new Scanner(System.in);
public void scan() {
System.out.println("?");
String answer = scan.nextLine().trim();
while (!answer.equalsIgnoreCase("EXIT")) {
System.out.println("?");
answer = scan.nextLine().trim().toUpperCase();
if (answer.equalsIgnoreCase("ADD")) {
add();
} else if (answer.equalsIgnoreCase("OBSERVATION")) {
observation();
} else if (answer.equalsIgnoreCase("STATISTICS")) {
System.out.println("jhjh");//just to see if this is
working
statistics();
}
}
}
below is the add method, also what I've commented is the attempts,
currently the add method does not have an if statements to decide duplicates.
public void add() {
System.out.print("Name: ");
String name1 = scan.nextLine().trim().toUpperCase();
System.out.print("Latin Name: ");
String latinName1 = scan.nextLine().trim().toUpperCase();
birds.add(new Bird(name1, latinName1));
/*
Bird newBird = new Bird(name1, latinName1);
for (int i = 0; i < birds.size(); i++) {
if (birds.get(i).getName().equals(name)) {
System.out.println("Bird already exist");
return;
} else {
birds.add(newBird);
}
}
/*
* hBirds.addAll(birds); birds = new ArrayList<Bird>();
birds.addAll(hBirds);
*
* // Bird newBird = new Bird(name, latinName);
* /* if(birds.contains(name)){
* System.out.println("That name already exist");
* return;
* }else{
* birds.add(newBird(name, latinName));
*
* }
*/
}
The statistics method prints out the ArrayList, a foreach loop that goes through the ArrayList prints it out. The expected result if I input seagull twice should be one seagull value not two. How do i reject the duplicate?
You can have two approaches here:
First: Traverse through ArrayList, if you can't find the same bird, add it to ArrayList. It is a worse approach.
Second: Store birds inside HashSet. In this case, you need to override .hashCode() and .equals(Object obj) methods. It is a better approach.
Before talking about how to generate .hashCode() and .equals(Object obj) methods, I want to mention about .hashCode() method and HashSet<T>.
HashSet<T>s provide a unique set of the elements inside. To achieve this, .hashCode() method of a class is used. If you override .hashCode() method in any class, you can get the benefit of using HashSet<T>s. If you don't override this method, Java automatically returns the memory address of the object. That's why your HashSet<Bird> was including duplicate elements.
.hashCode() and .equals() methods can be generated by lots of IDEs. I copied and pasted your Bird class to Eclipse. By using Alt+Shift+S -> h for Eclipse or Alt+Insert -> equals() and hashCode() for IntelliJ, automatically generated the methods below:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((latinName == null) ? 0 : latinName.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + obeservation;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bird other = (Bird) obj;
if (latinName == null) {
if (other.latinName != null)
return false;
} else if (!latinName.equals(other.latinName))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (obeservation != other.obeservation)
return false;
return true;
}
If you add these methods(I encourage you to generate in your IDE) to Bird class, you can use HashSet<Bird>. To avoid duplicates, simply add all of your Bird objects into defined HashSet<Bird>. You don't need any other data structure or equality check to control if any two Bird type objects are equal.
You will just need to change your object collection from ArrayList<Bird> birds = new ArrayList<Bird>(); to Set<Bird> birds = new HashSet<>();.
Move the add out of the loop:
for (int i = 0; i < birds.size(); i++) {
if (birds.get(i).getName().equals(name1)) {
System.out.println("Bird already exist");
return;
}
}
birds.add(new Bird(name1, latinName1));
I've been going through SO pages all morning trying to figure out the best way to attack my question:
What is the most efficient way to sort through an ArrayList, match on a name in the ArrayList with a name I'm pulling from a WebElement. I'm not experienced with Java, and wondering if this context it makes more sense to use HashTables, but I couldn't find an easily understandable answer on how to use them with multiple values per index:
My custom class:
public class KnowledgePermission {
public String name;
public String htmlType;
public Boolean isAllowed;
public KnowledgePermission(String name, String htmlType, Boolean isAllowed) {
this.name = name;
this.htmlType = htmlType;
this.isAllowed = isAllowed;
}
public String getName() {
return name;
}
public String getHtmlType() {
return htmlType;
}
public Boolean getIsAllowed() {
return isAllowed;
}
#Override
public boolean equals(Object obj) {
boolean result = false;
if(obj instanceof KnowledgePermission) {
KnowledgePermission otherPermission = (KnowledgePermission) obj;
result = (this.name == otherPermission.name);
}
return result;
}
#Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + htmlType.hashCode();
result = 31 * result + isAllowed.hashCode();
return result;
}
}
I'm able to use Java 8, so I've looked at filters, haven't been successful yet.
Here's the snippet after I've created a list using my class type.
What I'm trying to do is get the XPath of some browser page items, get its name via Selenium's WebDriver API, and for the one item I know should match in my permission list, access one of the other two properties - htmlType or isAllowed - and continue logic based off of that.
List<KnowledgePermission> permissionList = new ArrayList<KnowledgePermission>();
permissionList.add(new KnowledgePermission("checkbox1sName", "checkbox", true ));
permissionList.add(new KnowledgePermission("checkbox2sName", "checkbox", true ));
List<WebElement> checkboxes = driver.findElements(By.xpath("//*someXpathinfoHere//input[#type='checkbox']"));
// check the value of each checkbox and display
for(WebElement item : checkboxes) {
String elname = item.getAttribute("name");
Boolean hasBeenSelected = item.isSelected();
// find the permission in the list
System.out.println("filtering permissions list");
List<KnowledgePermission> currentPermission = permissionList.stream().filter(permission -> elname.equals(permission)).collect(Collectors.toList());
System.out.println(currentPermission);
}
All that prints out for each iteration of the loop is:
filtering permissions list
[]
So I'm guessing I'm not understanding filtering correctly here.
Any help and I'd be grateful!!
.filter(permission -> elname.equals(permission.getName()))
... is all you have to change
If elname can be null, change the order to
.filter(permission -> permission.getName().equals(elname))
Since instance.equals(null) returns false, not NullPointerException
I am trying to make an erase function to delete the teams of the tournament using the team code (value c in the constructor). Firstly I want to check if that team exists in the objects I made in the main method. Is that possible to do that using an if statement?
Exercise:
Create a java application that stores data for various football teams. Each team has a name, a code and the current points in the championship. In your class create methods for registering new teams, erasing existing teams using their code and showing a list for all the teams currently active in the championship
package assignment.exercise4;
public class Data {
private String name = "";
private int code = 0;
private static int register;
private int erase;
private int currentpoints = 0;
public Data(int c, int points, String n) { //constructor
code = c;
this.currentpoints = points;
name = n;
}
public void Erase(int c)
{
code = c;
if(code != 0)
System.out.println("Team with Code: "+code+" has been erased" );
else
System.out.print("Team with code "+code+" does not exist!");
}
public void Register(String newTeam,int code)
{
name = newTeam;
this.code = code;
System.out.println("New Team " + name + " registered with code " + code);
}
public void print()
{
System.out.println("Team name: " + name + "\nTeam code: " + code + "\nTeam points: " + currentpoints + "\n");
}
}
/*
public static void main(String[] args) {
System.out.println("\nList of Teams: \n");
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
Data Team = new Data(0,0,""); //use for erase
t1.print();
t2.print();
t3.print();
t4.print();
System.out.println("Teams erased: \n");
Team.Erase(110);
Team.Erase(122);
Team.Erase(0);
System.out.println("\n\nTeams Registered: \n");
t1.Register("Real madrid", 11);
t1.Register("Atletico Madric", 112);
}
}
*/
What are you trying to erase the teams from?
If they were in a list, for example...
Data t1 = new Data(110,42,"Juventus");
Data t2= new Data(105,45,"Manchester City");
Data t3= new Data(240,50,"Barcelona");
Data t4= new Data(122,36,"Arsenal");
List<Data> teams = Arrays.asList(t1, t2, t3, t4);
...you could create a list with a team erased like this...
public List<Data> erase(List<Data> team, int id) {
return team.stream()
.filter(t -> t.getId() != id)
.collect(Collectors.toList());
}
So...
List<Data> remainingTeam = erase(team, 122); // Removes Arsenal
...would remove the first element from the list
I will not answer this to elaborately since it is homework. I will try to give you a hint though.
If you have a team and want to do something with it. Otherwise you just have a team which just stays there in a particular scope (if you do not know what scope is, look it up!). If you have a team you most likely want do do something with it. In this case you seem to want to store information about the teams to use in a championship. Important to note here is that the teams are not the focus here. The real focus is the Championship. The teams are just a part of the championship. There can still be a championship even if all teams does not choose to participate. But you want all teams choosing to participate to be registered to this particular championship (eg UEFA Champions League).
This leads to something called aggregate or association depending on how hard you want to tie the object to the championship. However you do probably not need to pursue these terms any further at this point. What is important to remember is that there is an "has a" relation between the championship and the teams. The championship "has a" collection of participating teams. This is normally reflected in this way in code,
public class Championship {
private Team[] teams; // Or List<Team>, Collection<Team>, HashMap<Team>, ...
}
The Championship can then have methods for registering a team, removing a team, updating status, etc...
public void register(Team t) {
if (numberOfTeams < teams.length) {
teams[numberOfTeams] = t; // Index starts at zero
numberOfTeams++;
} else {
throw new IndexOutOfBoundsException("The list is full. " +
"No more teams may be registered!")
}
}
Even though the function erasing a team was requested, I believe I will not write it down. This design is so different from your original intent, so that writing the erase function will likely solve your complete homework. However, you do actually not have to erase the team it is perfectly possible to just overwrite the position with the next team as,
teams[i] = teams[i+1];
Hope this helps!
Short answer:
public void erase(int id) {
// who needs an if statement, if we can use predicates?
teams.removeIf(team -> team.getId() == id);
}
But this will not work with your current code. Your current code misses the container for your teams.
Longer answer:
For the fun of it. Solving your homework:
class Team {
int id;
String name;
int points;
Team(int id, String name, int points) {
this.id = id;
this.name = name;
this.points = points;
}
#Override
public String toString() {
// ugly formatted... another homework? ;-)
return "Team '" + name + "' (" + id + "): " + points;
}
}
Note, that I will not add any getter or setter, nor will I care about visibility here. I will leave that as another homework for you.
class Championship {
List<Team> teams = new ArrayList<>();
void register(Team team) {
teams.add(team);
}
void erase(int id) {
teams.removeIf(team -> team.id == id);
}
#Override
public String toString() {
// for additional fun... sorted by descending points
return "=== Championship table ===\n"
+ teams.stream()
.sorted((o1, o2) -> Integer.compare(o2.points, o1.points))
.map(Objects::toString)
.collect(Collectors.joining("\n"));
}
}
Somewhere else:
public static void main(String[] args) {
Championship championship = new Championship();
championship.register(new Team(1, "not the best ones", 3));
championship.register(new Team(2, "The better ones", 7));
championship.register(new Team(3, "The winners", 11));
System.out.println(championship);
championship.erase(3);
System.out.println(championship);
}
Output:
=== Championship table ===
Team 'The winners' (3): 11
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
=== Championship table ===
Team 'The better ones' (2): 7
Team 'not the best ones' (1): 3
Too much of information? Just start with something like a championship-class or at least use a collection of Teams (e.g. List<Team>).
By the way... Do not deliver this solution as your homework, except you understand what is going on and you can explain it with your own words. Otherwise you are only betraying yourself.
There is a collection of 20 objects of a POJO class. I Want to write a method that return objects with distinct value. Now this is my Pogo class
class Student {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName( String firstName ) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName( String lastName ) {
this.lastName = lastName;
}
}
Now i want some method which returns unique last names values. I could not understand which logic i have to put in this.
If you are using something like Eclipse, you can right-click the source and select Source > "Generate hashCode() and equals()...". Doing so will yield something like this:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
Then, you'll want to add your objects to an instance of Set, maybe HashSet. Sounds like you can just return the populated Set then.
See also this.
EDIT: Note that I am not suggesting to put all of this on the Student class. The code shown above goes on Student, but the method that returns the set of distinct students goes somewhere else.
EDIT 2: If you are only interested in unique last names, you could modify hashCode() and equals() to not consider first name, but I concede that this would be quite unintuitive and recommend to avoid this in any circumstance other than an academic exercise. So, more correct might be to layer on an instance of Comparator that only considers last name--see doc and this.
You can use an Arraylist, it has a built in function called .contains() which checks if the arrayList contains a specific value. So you would create an arrayList of last names and if it doesn't exist in the array list, just add it. See http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
You can try to use Set, if you need to get only one field, or Map, if you need to know object(student) with this field.
If you need to know all distinct Students (pair: first name + surname), you need to override getHashCode() and equals methods and use HashSet, HashMap
An easy way (for a beginner) to do this is just create a new array (same size of the input array). Then to loop through your array then compare every value to every other value in the array. If you can't find a match, then put this value in the new array.
Pseudo code:
public static Student[] GetUniqueLastNames(Student[] students){
Student[] retArray;//new array
for(i = 0; i < students.size; i++){
unique = true
for(j=0; j < students.size; j++){
if(i != j){//make sure its not comparing the same value
if(students[i].lastname.equals(students[j].lastname)){
unique = false
break
}
}
}
if(unique){
retArray[i] = students[i]
}
}
return retArray
}
Note: There are far better ways of doing this, but this is a nice basic way to do it if you're learning Java (or programming in general).
If you don't care about keeping the order of the objects, you can use a set:
public static <S extends Student> Collection<S> uniqByLastName(Collection<S> source){
TreeSet<S> result = new TreeSet<S>(new Comparator<S>() {
#Override
public int compare(S s1, S s2) {
return s1.getLastName().compareTo(s2.getLastName());
}
});
result.addAll(source);
return result;
}
If you care about the order
public static <S extends Student> Collection<S> uniqByLastName(Collection<S> source){
Collection<S> result = new ArrayList<S>();
Set<String> addedStudents = new HashSet<String>();
for(S student : source){
String lastName = student.getLastName();
if(!addedStudents.contains(lastName)){
result.add(student);
addedStudents.add(lastName);
}
}
return result;
}
If you want to modify the collection without returning a new one
public static <S extends Student> void uniqByLastName(Collection<S> source){
Set<String> addedStudents = new HashSet<String>();
Iterator<S> iterator = source.iterator();
while(iterator.hasNext()){
S student = iterator.next();
String lastName = student.getLastName();
if(addedStudents.contains(lastName)){
iterator.remove();
} else {
addedStudents.add(lastName);
}
}
}
If you are using Java 8, you can use lambda expression to solve it. Using following code snippet should solve your problem:
list.stream().collect(Collectors.toMap(Student::getLastName, p -> p, (p, q) -> p)).values();
Note: it will return first student with a given last name and as you might have already guessed, you don't need to override equals and hashcode.
I'm working on a project where I have to test to make sure certain code will meet user expectations. The only part I was supposed to do is write the code for GetCourseByCourseID. Everything else was given to me. I've written the code and run the program. The program runs, but it doesn't display anything. What do I need to do?
public class Course {
public Course(String id, String title, int creditHours, String description, String prerequisiteCourse)
{
this.CourseID = id;
this.CourseTitle = title;
this.CreditHours = creditHours;
this.Description = description;
this.PrerequisiteCourse = prerequisiteCourse;
}
public String CourseID;
public String CourseTitle;
public int CreditHours;
public String Description;
public String PrerequisiteCourse;
}
public class CourseList {
public Course[] CourseArray =
{
new Course ("CIS 400", "OO Analysis & Design", 4, "Important class", "CIS 110") ,
new Course ("CIS 150A" , "VB.NET Programming", 4, "Good Introduction to programming", "CIS 100") ,
new Course ("CIS 150B", "C# Programming with labs", 4, "Follow-up to CIS 100", "CIS 100")
};
public Course GetCourseByCourseID(String id)
{
for (Course course : CourseArray)
if (course.CourseID == id)
return course;
return null;
}
}
public class CourseListTest {
public static void main(String[] args)
{
GetCourseByCourseIDTestWhenCourseExists();
GetCourseByCourseIDTestWhenCourseDoesNotExist();
}
public static void GetCourseByCourseIDTestWhenCourseExists()
{
CourseList myCourseList = new CourseList();
Course myCourse = myCourseList.GetCourseByCourseID("CIS 400");
if (myCourse.CourseID != "CIS 400")
System.out.println("ERROR - GetCourseByCourseIDTestWhenCourseExists(): Returned CourseID Not equal (CIS 400)");
}
public static void GetCourseByCourseIDTestWhenCourseDoesNotExist()
{
CourseList myCourseList = new CourseList();
Course myCourse = myCourseList.GetCourseByCourseID("CIS 101");
if (myCourse != null)
System.out.println("ERROR - GetCourseByCourseIDTestWhenCourseDoesNotExist(): should have returned null");
}
}
This is for a class. I asked my professor why it wasn't showing up and he said he wasn't familiar with java and that I should use visual basic. I personally hate visual basic (bad experience with it in a prior class) and I would love to know how it works in java! I have looked everywhere for 2 hours and not found anything! Please help!
One of your problems is the line if (course.CourseID == id), which isn't comparing Strings correctly. You need to use equals, not == for String comparison, because == just checks whether two Strings are the actual same object in memory.
if (course.CourseID.equals(id))
This is explained in depth at How do I compare strings in Java?
You have the same problem on the line that says if (myCourse.CourseID != "CIS 400")
Try fixing those, and post a comment if your program still doesn't work.
course.CourseID == id
myCourse.CourseID != "CIS 400"
Change these two lines to:
course.CourseID.equals(id)
!myCourse.CourseID.equals("CIS 400")
See if you can get what you want.
Basically, you want to use String#equals to check for string equality instead of using ==.
public Course GetCourseByCourseID(String id){
for (Course course : CourseArray){
if (course.CourseID.equals(id)){
return course;
}
}
return null;
}
What you were doing was returning null on the first course before you could loop through the others.