java 作为整数的迭代器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35382032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:05:57  来源:igfitidea点击:

Iterator as an integer

javacompiler-errorsiterator

提问by MMCXCVII

As far as I?know, an Iterator is an object which type is defined during its declaration but which also comes with two other methods: hasNext()and next(). So, besides those two methods, if I write Iterator<Integer> iterator, then iterator is supposed to behave like an Integer object. However, when I try to use iterator.intValue(), I get an error.

据我所知,迭代器是一个对象,其类型在其声明期间定义,但还带有其他两个方法:hasNext()next()。所以,除了这两种方法,如果我写Iterator<Integer> iterator,那么迭代器应该表现得像一个 Integer 对象。但是,当我尝试使用 时iterator.intValue(),出现错误。

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method intValue() is undefined for the type Class<capture#1-of ? extends Iterator>
    Syntax error, insert "}" to complete Block

Here is the full code:

这是完整的代码:

    Iterator<Integer> iterator = content.iterator(); //content is a HashSet<Integer> object
    System.out.println(iterator.intValue());

    while(iterator.hasNext())
    {
        iterator.next();
        System.out.println(iterator);

    }

回答by Greg Valcourt

You need to get the Integer from the iterator, then print that Integer:

您需要从迭代器中获取整数,然后打印该整数:

Integer i = iterator.next();
System.out.println(i);

An Iterator is an iterator for integers, it doesn't behave like an integer. The next method will return an Integer.

Iterator 是整数的迭代器,它的行为不像整数。下一个方法将返回一个整数。

回答by Mureinik

No, an Iterator<T>does not act like a T- its next()method, however, returns a T value. I.e.:

不, anIterator<T>不像 a T- 它的next()方法,但是,返回一个 T value。IE:

while(iterator.hasNext()) {
    Integer myInteger = iterator.next();
    int myInt = myInteger.intValue();
}

回答by Peter Lawrey

An Iterator is not an Integer, though it might give you one if you call next()Instead of calling the Iterator directly is usually better to use a for-each loop which was added to Java 5.0 in 2006.

Iterator 不是 Integer,但如果您调用它可能会给您一个,next()而不是直接调用 Iterator 通常最好使用 2006 年添加到 Java 5.0 的 for-each 循环。

for(int n : content) //content is a HashSet<Integer> object
    System.out.println(n);

From Java 8 you can use the forEach method.

从 Java 8 开始,您可以使用 forEach 方法。

content.forEach(System.out::println);

回答by afroz1198

More Precisely,iterator.next()returns an Object type variable.So,typecastingis necessary

更准确地说,iterator.next()返回一个 Object 类型的变量。所以,typecasting是必要的

Integer myInteger = (Integer) iterator.next();
int i = myInteger.intValue();