Java 集合框架Example-Set

来源:互联网 发布:paxos算法 应用 编辑:程序博客网 时间:2024/05/01 18:25

Set 无get()方法

案例:

  • 提供备选课程
  • 创建学生对象,并给该学生添加三门课程(添加在学生的courses----Set类型的属性中)
    • 显示备选课程
    • 循环三次,每次输入课程ID
    • 往学生的courses属性中添加与输入的ID匹配的课程
    • 输出学生选择的课程
Set中,添加某个对象,无论添加多少次,最终只会保留一个该对象,并且,保留的是第一次添加的那一个

Set中可添加NULL对象

import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;public class SetTest {public List<Course> coursesToSelect;public SetTest(){coursesToSelect =new ArrayList<Course>();}public void testAdd(){/* * 创建一个课程对象,并通过调用add,添加list中 */Course cr1=new Course("1"," 数据结构");coursesToSelect.add(cr1);//Course temp=(Course) coursesToSelect.get(0);//System.out.println("添加了:"+temp.id+temp.name);Course cr2= new Course("2"," C language");coursesToSelect.add(1,cr2);//Course temp2=(Course) coursesToSelect.get(0);//System.out.println("添加了:"+ temp2.id+temp2.name);Course[] course={new Course("3"," 离散数学"),new Course("4"," 汇编语言")};coursesToSelect.addAll(Arrays.asList(course));//Course temp3=(Course) coursesToSelect.get(3);//Course temp4=(Course) coursesToSelect.get(4);//System.out.println("添加了:" + temp3.id+temp3.name+";"+temp4.id+temp4.name);Course[] course2={new Course("5"," 高等数学"),new Course("6"," 大学英语")};coursesToSelect.addAll(Arrays.asList(course2));//Course temp5=(Course) coursesToSelect.get(2);//Course temp6=(Course) coursesToSelect.get(3);//System.out.println("添加了:" + temp5.id+temp5.name+";"+temp6.id+temp6.name);}public void testForEach(){for (Course cr:coursesToSelect){System.out.println("课程: "+cr.id+":"+cr.name);}}public static void main(String[] args) {SetTest st=new SetTest();st.testAdd();st.testForEach();      /*     * 创建学生对象    */  Student student=new Student("1", "Vivian");System.out.println("欢迎学生: "+student.name+"选课");//创建一个Scanner对象,用来接受从键盘输入的课程IDScanner input=new Scanner(System.in);for(int i=0;i<3;i++){System.out.println("请输入字符ID:");String courseid=input.next();for(Course cr:st.coursesToSelect){if(cr.id.equals(courseid)){student.courses.add(cr);}}}st.testForEachForSet(student);}public void testForEachForSet(Student student){//打印输出,学生所选课程for(Course cr:student.courses){System.out.println("选择了课程:"+ cr.id+cr.name);}}


0 0