Yield Return In Java

后端 未结 10 1251
春和景丽
春和景丽 2020-12-13 23:13

I\'ve created a linked list in java using generics, and now I want to be able to iterate over all the elements in the list. In C# I would use yield return insid

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 23:48

    Just to help readers understand the small details.

    If you create a new list containing all the resulting elements and return the list, then this is a good implementation, simple enough to code. You can have as interesting data structure as you need, and when scanning it for the right entries, just return a list of all the matches, and your client will iterate on the list.

    If you want to save a state, it may be more complicated. You'll need to get to where you've been every time your function is called. Not to mention re-entrant issues, etc.

    The solution with threads does not create a new list. And it is as simple as the first solution. The only issue is that you involve a thread synchronization which is a bit more hard to code, and has its performance penalties.

    So, yes, yield return is great and is missing from Java. Yet there are workarounds.

提交回复
热议问题