JAVA基础 - Collection集合存储自定义类型的对象
一、Movies.java
package com.java.base; /* 需求:某影院系统需要在后台存储上述三部电影,然后依次展示出来 分析: 1、定义一个电影类,定义一个集合存储电影对象 2、创建3个电影对象,封装相关数据,把3个对象存入到集合中去 3、遍历集合中的3个对象,输出相关信息 */ public class Movies { private String name; private double score; private String actor; public Movies() { } public Movies(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 "Movies{" + "name='" + name + '\'' + ", score=" + score + ", actor='" + actor + '\'' + '}'; } }
二、MoviesTest.java
package com.java.base; import java.util.ArrayList; import java.util.Collection; public class MoviesTest { public static void main(String[] args) { Collection<Movies> movies = new ArrayList<>(); movies.add(new Movies("<你好>",9.5,"沈腾")); movies.add(new Movies("<刺杀>",9.1,"王宝强")); for (Movies mo : movies){ System.out.println(mo);//这种写法输出的是集合的地址com.java.base.Movies@685f4c2e,
当Movies类重写了toString方法后,输出的是Movies{name='<你好>', score=9.5, actor='沈腾'} //可以通过get方法获取集合信息 System.out.println("片名:"+mo.getName()); System.out.println("得分:"+mo.getScore()); System.out.println("主演:"+mo.getActor()); } } }
三、输出结果
四、list集合的遍历方式
package com.java.base; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; public class MoviesTest { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("张三丰"); list.add("李白"); list.add("java"); //在某个索引位置插入元素 list.add(2,"html"); System.out.println(list); //根据索引删除元素,返回被删除元素 list.remove(2); System.out.println(list); //根据索引获取元素,get返回集合中指定位置的元素 System.out.println(list.get(2)); //修改索引位置处的元素,set System.out.println(list.set(1,"张无忌")); System.out.println(list); //for循环 for(int i = 0;i<list.size();i++){ String ele = list.get(i); System.out.println(ele); } //迭代器 Iterator<String> iterator = list.iterator(); while (iterator.hasNext()){ String ele = iterator.next(); System.out.println(ele); } //foreach for(String ele : list){ System.out.println(ele); } //lambda表达式 list.forEach(s -> { System.out.println(s); }); } }