为什么在java中有两种不同的for循环? [英] why are there two different kinds of for loops in java?

查看:110
本文介绍了为什么在java中有两种不同的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个循环,我不知道它是如何工作的。我熟悉:

$ p $ for(int i = 0; i <= 9; i ++)
{
/ * implementation * /
}

如下形式:

  String [] myString = new String [] {one,two,three, 一些其他的东西}; 

String str1 =,str2 =;
$ b $(b












$ p>

这些类型的对于循环是如何工作的?他们做什么不同,然后定期循环?

第一个是原来的循环。你初始化一个变量,设置一个终止条件,并提供一个状态递增/递减计数器(有例外,但这是经典)

为此,

  for(int i = 0; i< myString.length; i ++){
System.out.println(myString [i ]);



$ b

是正确的。

$ b <对于Java 5,提出了一个替代方案。任何实现迭代的东西都可以被支持。这在集合中特别好。例如你可以像这样迭代列表。

  List< String> (=字符串:列表){
System.out.println(string);

而不是

<$ (int i = 0; i< list.size(); i ++){
System.out.println(list.get(i));





$ b

所以这只是一个替代符号。任何实现Iterable的项目(即可以返回一个迭代器)都可以这样写。

后台发生的事情是这样的:(更有效率,但是我明确写到)

 迭代<字符串> it = list.iterator(); $()。()()()$ {
String string = it.next();
System.out.println(string);



$ b $ p
$ b

最后,它只是语法上的糖,但相当方便。


I have a for loop, and I am not sure how it works. I am familiar with:

for(int i = 0; i <= 9; i++)
{
    /* implementation */
}

I am confused about a for loop in the following form:

String[] myString = new String[] {"one", "two", "three", "some other stuff"};

String str1 = "", str2 = "";  

for (String s :  myString)
{
    /* implementation */
}

How do these types of for loops work? what do they do differently then regular for loops?

解决方案

The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)

For that,

for (int i=0;i<myString.length;i++) { 
  System.out.println(myString[i]); 
}

is correct.

For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this

List<String> list = ....load up with stuff

for (String string : list) {
  System.out.println(string);
}

instead of

for (int i=0; i<list.size();i++) {
  System.out.println(list.get(i));
}

So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.

What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  String string=it.next();
  System.out.println(string);
}

In the end it's just syntactic sugar, but rather convenient.

这篇关于为什么在java中有两种不同的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆