I am trying to solve this problem but having some bugs in it. [Note: I am just using simple partially filled arrays ] [No fancy Array List or Lists is allowed]
I have two classes Student.java and StudentList.java
Student.java has following conditions:
1. It has 3 instance variables student (String) name, (String) last name and ( int )student number
2. It has constructor that initializes all three instance variables.
3. It has a toString method that returns in following format : Dillon, Mike (1234567) 4. An equals method that checks if two students are equal if all three fields name , last name and student number match
This is my implementation:
StudentList.java has following conditions:
1.Three instance varibales : an array of students, max size of array (int) and current number of students in the array(int)
2. A constructor that takes one parameter: the maximum size of the array. The other instance variables must be initialized in the constructor (assume that the StudentList will be empty when constructed)
3. method contains(Student) that checks if the student is already in the list and returns a boolean (true if in the list or false otherwise).
4.A method addStudent that has a parameter of type Student, adds the Student to the list only if there is enough space. This method returns a boolean (true if the student was added and false otherwise)
5. toString method which returns a String containing all the Students in the list
This is my implementation of StudentList.java
The problem I am getting is if I add Student1, Student2, Student3, Student4, Student5 they add correctly and when i try to add Student1 again everything is correct. But if I add anymore duplicate students and there is space in array it still adds them.
The equals() method should be overridden,, not as you have it there, overloaded. It takes Object as its parameter. You also need to override the hashCode() method whenever you override equals().
See, for example, Joshua Bloch's Effective Java, or search for Angelika Langer Java equals hashCode or loo at Odersky Spoon and Venners. If you have enough time, read all three resources. If you overload equals(), you can rely on collections containing your object not working correctly.
Consider using this method in your constructor to prevent anybody passing nulls (not required for the int parameter). The link shows an example of how it can be used in a constructor.