0

I have usersArrayList, messagesArrayList and chatsArrayList, that are ArrayList<User>, ArrayList<Message> andArrayList<Chat> respectively. Each of these classes has an id attribute.

I tried to write a generic function to find instance of given object in given list by id like that:

public static <T> T findInListById(ArrayList<T> list, String objId) {
        return list.stream().filter(listObj -> listObj.id.equals(objId)).findFirst();
}

But Java says that listObj doesn't have an id attribute. How do I write function so it works for User, Chat and Message classes?

P.S. I also tried writing a parent class IDClass for all of them, which solved the problem, but then when I tried to invoke it (ID.findInListById(usersArrayList,userId)), Java would complain:

Required Type: ArrayList<ID>
Provided: ArrayList<User>
LazySlav
  • 21
  • 2
  • 1
    probably you must declare `` as ``, that is, `public static T findInListById(...` - no idea what class `ID` from the error is... – user16320675 May 26 '23 at 06:36
  • 1
    Unify the types using a type that exposes the ID. For example, your `IDClass` class. Then change the type parameter bounds to ``. You might also want to change the `list` parameter to be a `Collection extends T>` (the `Collection` interface because it's typically best to be as abstract as possible, and the `? extends T` because the semantics of the method mean `list` is being used as a producer). – Slaw May 26 '23 at 06:37

0 Answers0