Set


package onlinejudge;
import java.util.*;  
/*
 * Set接口及其实现类--HashSet
 * Set是元素无序并且不可以重复的集合,被称为集
 * HashSet哈希集,是Set重要实现类
 * 
 * Set遍历只可以用Foreach 和 Iterator , 不可以用get方法
 */
class Course{  
    public String id;  
    public String name;  
    public Course(String id, String name){  
        this.id = id;  
        this.name = name;  
    }  
}  
class Student{  
    String id;  
    String name;  
    Set <Course> courses;// Set is interface  
    Student(String id, String name){  
        this.id = id;  
        this.name = name;  
        this.courses = new HashSet<Course>();  
        //HashSet is Set's class  
    }  
}  
class SetTest{
	List<Course> coursesToSelect;
	SetTest(){
		this.coursesToSelect = new ArrayList<Course>();
	}
	void testAdd() {
		Course cr1 = new Course("1" , "数据结构");
		coursesToSelect.add(cr1);
		Course cr2 = new Course("2" , "离散数学");
		coursesToSelect.add(cr2);
		Course cr3 = new Course("3" , "大学英语");
		coursesToSelect.add(cr3);
		Course cr4 = new Course("4" , "Java基础");
		coursesToSelect.add(cr4);
	}
	void Foreach() {
		for(Course cr : coursesToSelect) {
			System.out.println(cr.id + " " + cr.name);
		}
	}
}
public class Main {
   public static void main(String []args) {
	   SetTest st = new SetTest();
	   st.testAdd();
	   st.Foreach();
	   //创建一个新的学生对象
	   Student student = new Student("1","小明");
	   System.out.println("欢迎学生:"+ student.name+ " 选课");
	   Scanner cin = new Scanner(System.in);
	   for( int i = 0;i<3;i++) {
		   System.out.println("请输入课程id");
		   String courseID = cin.next();
		   for(Course cr : st.coursesToSelect) {
			   if(cr.id.equals(courseID)) {
				   student.courses.add(cr);
			   }
		   }
	   }
	   for(Course cr:student.courses) {
		   System.out.println("选择了课程:"+ cr.id + " " + cr.name);
	   }
	   cin.close();
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值