Collection接口和常用方法2

方法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 }
复制代码

 

posted @   Unagi  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示