Collection集合存储自定义类型的对象
-
案例:影片信息在程序中的表示
-
需求:某影院系统需要在后边存储上述三部电影,然后依次展示出来
-
分析:
- 定义一个电影类,定义一个集合存储电影对象
- 创建三个电影对象,封装相关数据,把三个对象存入到集合中去
- 遍历集合中的3个对象,输出相关信息
-
测试代码
package com.java.collection; public class Movie { private String name; private double score; private String actor; public Movie() { } public Movie(String name, double score, String actor) { this.name = name; this.score = score; this.actor = actor; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public String getActor() { return actor; } public void setActor(String actor) { this.actor = actor; } @Override public String toString() { return "Movie{" + "name='" + name + '\'' + ", score=" + score + ", actor='" + actor + '\'' + '}'; } }
package com.java.collection; import java.util.ArrayList; import java.util.Collection; public class MovieTestDemo { public static void main(String[] args) { Collection<Movie> movies = new ArrayList<>(); // 多态存在访问问题,左边的父类不能调用右边的子类方法 // 因此不能使用for循环遍历Collection movies.add(new Movie("《头文字D》",9.8,"陈冠希")); // 直接new出并代入,加进来的是地址 movies.add(new Movie("《头文字D》",9.8,"张柏芝")); movies.add(new Movie("《武郎卖饼》",6.8,"谢霆锋")); System.out.println(movies); // 前提是Movie类重写toString()方法 for (Movie movie : movies) { System.out.println("片名:" + movie.getName()); System.out.println("评分:" + movie.getScore()); System.out.println("主演:" + movie.getActor()); System.out.println(); } } }
- 集合中存储的是元素对象的地址
网友评论