今天看一资料,有如下程序,编译没有问题。。enum CoffeeSize {
BIG( 8 ), HUGE( 10 ), OVERWHELMING( 16 );
// 8, 10 & 16 are passed to the constructor
CoffeeSize( int $ounces ) {
// constructor
this.ounces = $ounces;
} private int ounces; // an instance variable public int getOunces()
{
return ounces;
}
}class Coffee1 {
CoffeeSize size; // each instance of Coffee has an enum public static void main( String args[] )
{
Coffee1 drink1 = new Coffee1();
drink1.size = CoffeeSize.BIG; Coffee1 drink2 = new Coffee1();
drink2.size = CoffeeSize.OVERWHELMING; System.out.println( drink1.size.getOunces() );
for(CoffeeSize cs: CoffeeSize.values()) // ??!!!!!!!!!!!!!!!!!!
System.out.println( cs + " " + cs.getOunces() );
}
}for(CoffeeSize cs: CoffeeSize.values()) // ??!!!!!!!!!!!!!!!!!!
System.out.println( cs + " " + cs.getOunces() );
这个for循环为什么是正确的- -麻烦大家了~~
BIG( 8 ), HUGE( 10 ), OVERWHELMING( 16 );
// 8, 10 & 16 are passed to the constructor
CoffeeSize( int $ounces ) {
// constructor
this.ounces = $ounces;
} private int ounces; // an instance variable public int getOunces()
{
return ounces;
}
}class Coffee1 {
CoffeeSize size; // each instance of Coffee has an enum public static void main( String args[] )
{
Coffee1 drink1 = new Coffee1();
drink1.size = CoffeeSize.BIG; Coffee1 drink2 = new Coffee1();
drink2.size = CoffeeSize.OVERWHELMING; System.out.println( drink1.size.getOunces() );
for(CoffeeSize cs: CoffeeSize.values()) // ??!!!!!!!!!!!!!!!!!!
System.out.println( cs + " " + cs.getOunces() );
}
}for(CoffeeSize cs: CoffeeSize.values()) // ??!!!!!!!!!!!!!!!!!!
System.out.println( cs + " " + cs.getOunces() );
这个for循环为什么是正确的- -麻烦大家了~~
for(CoffeeSize cs: CoffeeSize.values())
System.out.println( cs + " " + cs.getOunces() );而且,上面这个要比下面这个:
for(int i=0; i<CoffeeSize.values().size(); i++)
System.out.println( cs + " " + CoffeeSize.values().get(i).getOunces() );
效率要高;
for(CoffeeSize cs: CoffeeSize.values())
System.out.println( cs + " " + cs.getOunces() );
楼主可以百度下
for (Grade g : Grade.values()) {
out.println("Allowed value: '" + g + "'");
}
}