Monday, 15 February 2010

java - Default Iterable plus other Iterable -



java - Default Iterable plus other Iterable -

i have class methods returning different iterable this:

public class myclass<t extends comparable<t>> { ... public iterable<t> iterable1() { homecoming new iterable1<t>(); } public iterable<t> iterable2() { homecoming new iterable2<t>(); } public iterable<t> iterable3() { homecoming new iterable3<t>(); } }

but want default iterable class myclass (let's iterable1). know create myclass extend iterable , implement default policy within it, not want because want clean interface.

i want able write:

for(t t : myclass) //here should utilize iterable1 //do

or

for(t t : myclass.iterable1()) //here should utilize iterable1 1 time again //do

and

for(t t : myclass.iterable2()) //here uses iterable2 //do

and on. can not think of many pattern accomplish this, though.

your top level class needs implement iterable. iterable interface defines method

iterator<t> iterator();

which provide 'default' iterator in case.

your class need little this:

public class myclass<t extends comparable<t>> implements iterable<t> { ... iterator<t> iterator() { homecoming new iterable1<t>().iterator(); } public iterable<t> iterable1() { homecoming new iterable1<t>(); } public iterable<t> iterable2() { homecoming new iterable2<t>(); } public iterable<t> iterable3() { homecoming new iterable3<t>(); } }

java iterator iterable

No comments:

Post a Comment