Dhiraj_N
Dhiraj_N

Reputation: 51

Iterating through generic List of Object type

I am trying to get values from a object type generic List. And I want to put some condition on value of one attribute of that class. For example I have Bean class User

class User {
    private String firstName;
    private String lastName;
    private String companyName;
    //Getters and Setters
}

I have stored three records of this in table. like (FIRST_NAME , LAST_NAME , COMPANY_NAME) (John,Woods,Persistent) (Bill,Gates,Microsoft) (Steve,Jobs,Apple)

And when I am getting these records from table it's in a list like this

List<T> list = query.getResultList();

Now I want to check if any user has lastName = Jobs then change the value of Company to Google.

Someone please tell me how should I do this.

Upvotes: 2

Views: 15967

Answers (3)

Wyzard
Wyzard

Reputation: 34591

You can't make a generic method do different things based on the type of T.

In a List<T>, there are no limitations on what type T can be, so all that it's known is that it's an object of some kind and you can only call methods that work on any object (i.e. methods defined in the Object class). Basically, a variable of type T is effectively a variable of type Object at runtime.

You can use instanceof and casts to check whether the object is of a particular type:

for (T item : list) {
    if (item instanceof User) {
        User user = (User) item;
        // ...
    }
}

But this isn't really related to generics; you're not looking at the type of T, just the type of each individual object in the list.

Upvotes: 2

RockOnRockOut
RockOnRockOut

Reputation: 761

for(T element : list){
    if((element instanceof User) && (element.getLastName().equals("Jobs")))
        element.setCompany("Google");
}

And you will need setters and getters, since those fields are private.

Upvotes: -2

FrobberOfBits
FrobberOfBits

Reputation: 18022

In the general case you can do this:

for(T item : list) { 
    if(item instanceof User && "Jobs".equals(((User)item).getLastName())) { 
         // Change company to google.
    }
} 

Upvotes: 6

Related Questions