elpasso
elpasso

Reputation: 99

Method with different List parameter

Hi all I think I have a trivial question, but I cannot handle it :(

I have a two Lists of different Objects, but those Objects have one the same method. I wish to pass the List to a method and execute Object method:

List<Job> list = new ArrayList<Job>();
Job j1 = new Job();
j1.setName("ddddd");
list.add(j1);
Job j2 = new Job();
j2.setName("fffff");
list.add(j2);


List<JobItem> list2 = new ArrayList<JobItem>();
JobItem j3 = new JobItem();
j3.setName("ttttt");
list2.add(j3);
JobItem j4 = new JobItem();
j4.setName("bbbbb");
list2.add(j4);

listItems(list);

private void listItems(List<?> list) {
    for (int i = 0; i < list.size(); i++) {
        Job ff = (Job) list.get(i);
        System.out.println(ff.getName());
    }
}

This example works, but how can I pass also list2 List

Thank you for help.

Upvotes: 2

Views: 64

Answers (1)

SLaks
SLaks

Reputation: 887453

Make a common base class or interface that contains the methods you need.

Then, change the method to take a List<? extends JobBase>.

Upvotes: 3

Related Questions