方法2:
增强for循环:可以代替iterator迭代器
特点:增强for就是简化版的iterator,本质一样,只能用于遍历集合或者数组
基本语法:
for(元素类型 元素名:集合名或数组名){
访问元素
}
1 public class CollectionMethod2 { 2 @SuppressWarnings({"all"}) 3 public static void main(String[] args) { 4 Collection col = new ArrayList(); 5 col.add(new Book("三国演义","罗贯中", 19.9)); 6 col.add(new Book("小李飞刀","古龙", 59.9)); 7 col.add(new Book("红楼梦","曹雪芹", 9.9)); 8 9 //使用增强for循环 10 //增强for也可以直接对数组使用 11 //增强for底层还是迭代器 12 //快捷方式I 13 for(Object book : col){ 14 System.out.println(book); 15 } 16 17 } 18 } 19 20 class Book{ 21 private String name; 22 private String author; 23 private double price; 24 25 public Book(String name, String author, double price) { 26 this.name = name; 27 this.author = author; 28 this.price = price; 29 } 30 31 public String getName() { 32 return name; 33 } 34 35 public void setName(String name) { 36 this.name = name; 37 } 38 39 public String getAuthor() { 40 return author; 41 } 42 43 public void setAuthor(String author) { 44 this.author = author; 45 } 46 47 public double getPrice() { 48 return price; 49 } 50 51 public void setPrice(double price) { 52 this.price = price; 53 } 54 55 @Override 56 public String toString() { 57 return "Book{" + 58 "name='" + name + '\'' + 59 ", author='" + author + '\'' + 60 ", price=" + price + 61 '}'; 62 } 63 }
标签:常用,String,author,price,接口,Book,Collection,public,name From: https://www.cnblogs.com/unagi/p/16876090.html