I have used below method to check record present in the table.
private static boolean isPresent(StuPersonal object, List<StuPersonal> list)
{
for (StuPersonal candidate : list) {
if (candidate.getFRID().equals(object.getFRID()))
{
return true;
}
}
return false;
}
here StuPersonal is a class and list is a list of class StuPersonal. I need to reuse this method for different classes. How can I do it? I have StuDegree,StuContact,StuCollege,etc and its lists. The process must be done when I pass the classes object and its list. Please advise..
If all of these classes have a getFRID()
method, then that should be in an interface (e.g. Identified
). Then you can use:
private static <T extends Identified> boolean isPresent(T object, List<T> list) {
String frid = object.getFRID(); // Adjust type appropriately
for (Identified item : list) {
if (item.getFRID().equals(frid)) {
return true;
}
}
return false;
}
Alternatively, as a non-generic method - slightly less safe as it means you can try to find a StuPersonal
within a List<StuContact>
or whatever:
private static boolean isPresent(Identified object, List<? extends Identified> list) {
String frid = object.getFRID(); // Adjust type appropriately
for (Identified item : list) {
if (item.getFRID().equals(frid)) {
return true;
}
}
return false;
}
Consider using Iterable
instead of List
, too.
See more on this question at Stackoverflow