本文介绍了Java的收益率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用泛型在 java 中创建了一个链表,现在我希望能够遍历列表中的所有元素.在 C# 中,我会在链接列表中使用 yield return,同时遍历列表中包含的元素列表.

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 inside the linked list while going over the list of elements contained in the list.

我将如何创建上述的 Java 版本,以便我可以迭代链接列表中包含的所有项目?

How would I go about creating a java version of the above where I can iterate over all the items contained in the linked list?

我希望能够编写代码 ala

I'm looking to be able to write code ala

LinkedList<something> authors = new LinkedList<something>();
for (Iterator<something> i = authors.Values ; i.HasNext())
      doSomethingWith(i.Value);

并且认为 Value 'property'/method 将包含类似的代码

And was thinking that the Value 'property'/method would consist of code resembling

LinkedListObject<something> current = first;
While (current != null){
 yield return current.getValue();
 current = current.getNext()
}

请注意,我对使用任何 3rd 方 API 不感兴趣.仅内置 java 功能.

Notice that I'm not interested in using any 3rd party APIs. Built-in java functionality only.

推荐答案

您可以返回 Iterable 的匿名实现.效果非常相似,只是这更冗长.

You can return an anonymous implementation of Iterable. The effects are pretty pretty similar, just that this is a lot more verbose.

public Iterable<String> getStuff() {
    return new Iterable<String>() {

        @Override
        public Iterator<String> iterator() {
            return new Iterator<String>() {

                @Override
                public boolean hasNext() {
                    // TODO code to check next
                }

                @Override
                public String next() {
                    // TODO code to go to next
                }

                @Override
                public void remove() {
                    // TODO code to remove item or throw exception
                }

            };
        }
    };
}

这篇关于Java的收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:12