This is precisely why you should be using generics! You risk to encounter runtime errors (as opposed to compile-time errors) involving expected and actual types.
Your call to list.get()
will return Object
if generics are not used, requiring you therefore to cast it. If the cast happens to be wrong as in your case, it will explode only when run. If you were using generics, your compiler would have told you that you can't convert a Student
type to String
type!
Take a look at my version:
public class Student {
int rollNo, yearOfStudy;
String fName, lName, activity;
public Student(int rollNo, String fName, String lName, int yearOfStudy) {
this.rollNo = rollNo;
this.fName = fName;
this.lName = lName;
this.yearOfStudy = yearOfStudy;
}
@Override
public String toString() {
return new StringBuilder()
.append("Roll Number: ").append(rollNo)
.append("\nName: ").append(fName).append(" ").append(lName)
.append("\nYear Of Study: ").append(yearOfStudy)
.append("\n\n")
.toString();
}
public void messFood() {
// Establish mess food charge role
}
public static void main(String[] args) {
Student s1 = new Student(1, "Alex", "Iwobi", 2013);
Student s2 = new Student(2, "Denis", "Suarez", 2013);
Student s3 = new Student(3, "Gerard", "Deulofeu", 2013);
Student s4 = new Student(4, "Petr", "Cech", 2013);
List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
Iterator<Student> it = studentList.iterator();
while (it.hasNext()) {
Student s = it.next();
System.out.println(s.toString());
}
Student randomStudent = getRandomItem(studentList);
randomStudent.messFood();
System.out.println("week 1, Mess food Incharge: ");
System.out.println(randomStudent.toString());
}
private static <T> T getRandomItem(List<T> studentList) {
return studentList.get(new Random().nextInt(studentList.size()));
}
}
Also, in addition to generics, I added a couple of best practices, namely prefering the use of toString()
to describe the class rather than printing it out directly (you can do with the String
whatever you want afterwards, including calling System.out.println()
) .
Also I moved out printing from messFood
because again, it is generally preferable to do so. Hope that helps!
Edit: Describing briefly getRandomItem
, try not to get too caught up in the details, but <T>
says that there will be a type to replace T
according to how it will be called. Based on how it is defined, it says if you pass me a List
containing type T
, I will return to you an object T
. T
in this case translates to Student
, but I kept it generic because it works equally well with other lists. For all intents and purposes, it is as if the signature were the following:
private static Student getRandomItem(List<Student> studentList)