2

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.

4

1 回答 1

3

创建一个包含所需方法的通用基类或接口。

然后,更改方法以采取List<? extends JobBase>.

于 2013-10-18T14:43:52.580 回答