I have two methods like the following
private List<Long> getIds(String name, List<Cat> cats) {
List<Long> catIds = new ArrayList<>();
for (Cat cat : cats) {
if (cat.getName().equals(name)) catIds.add(cat.getId());
}
return catIds;
}
private List<Long> getIds(String name, List<Dog> dogs) {
List<Long> dogIds = new ArrayList<>();
for (Dog dog : dogs) {
if (dog.getName().equals(name)) dogIds.add(dog.getId());
}
return dogIds;
}
My cat and dog class are as follows
public class Cat {
String name;
Long id;
// additional variables
// getters and setters
}
public class Dog {
String name;
Long id;
// additional variables
// getters and setters
}
Just to avoid redundancy, I wanted to convert the above two methods to a single generic method.
I tried the following
private List<Long> getIds(String name, List<T> objects) {
List<Long> ids = new ArrayList<>();
for (T object : objects) {
if (object.getName().equals(name)) ids.add(object.getId());
}
return ids;
}
But it does not work out as it complains that the generic T does not have getName or getId
Here Cat and Dog are in-built java classes. As a result I CANNOT perform inheritance and provide a super class Animal for them with name and id as data variables.
Is there any way I could accomplish merging the two above methods without implementing inheritance?