Reputation: 189
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..
Upvotes: 1
Views: 1341
Reputation: 13535
<S extends Stu>boolean isPresent(S object, List<S> list) {
for (StuPersonal candidate : list) {
if (candidate.getFRID().equals(object.getFRID())) {
return true;
}
}
return false;
}
where type Stu
is a common superclass or interface of types StuDegree,StuContact,StuCollege,etc, which has method getFRID()
.
Upvotes: 0
Reputation: 1503579
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.
Upvotes: 4
Reputation: 9331
Let each class define equals()
method. And then you can just do list.contains(object)
which will return boolean
. This is the most preferred solution.
Upvotes: 2