Mahes_sa_jey
Mahes_sa_jey

Reputation: 189

how to pass objects and list dynamically in a method?

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

Answers (3)

Alexei Kaigorodov
Alexei Kaigorodov

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

Jon Skeet
Jon Skeet

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

Saša Šijak
Saša Šijak

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

Related Questions