java集合练习

package com.imooc.collection;
/**
 * 课程类
 * @author admin
 *
 */
public class Course {
	public String id;
	public String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Course(String id, String name){
		this.id = id;
		this.name = name;
	}
	public void HaHa(String id, String name) {
		this.id = id;
		this.name = name;
	}
	/**
	 * 作为父类使用, 由于子类会自动调用父类的无参构造器
	 * 因此需要创建一个无参构造器
	 */
	public Course(){
		
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		//判断类型两种写法
//		if (getClass() != obj.getClass())
//			return false;
		//或者
		if(!(obj instanceof Course)) {
			return false;
		}
		Course other = (Course) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
}
package com.imooc.collection;

import java.util.HashSet;
import java.util.Set;

/**
 * 学生类
 * @author admin
 *
 */
public class Student {
	public String id;
	public String name;
	//由于学生能选择很多课, 创建学生课程的属性
	public Set
   
   
    
     course;
	public Student(String id, String name){
		this.id = id;
		this.name = name;
		//初始化course
		this.course = new HashSet
    
    
     
     ();
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((course == null) ? 0 : course.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (course == null) {
			if (other.course != null)
				return false;
		} else if (!course.equals(other.course))
			return false;
		return true;
	}
}
package com.imooc.collection;

import java.util.ArrayList;
import java.util.List;

public class TestFanXing {
	/**
	 * 使用泛型管理
	 * 使用泛型可以控制输入的类型
	 * @param args
	 */
	//定义由泛型控制的属性
	public List
     
     
      
       courses;
	//构造器初始化
	public TestFanXing(){
		this.courses = new ArrayList
      
      
       
       ();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TestFanXing f = new TestFanXing();
		f.add();
		f.ForEach();
	}
	
	public void add(){
		Course cr = new Course("1", "思想政治");
		courses.add(cr);
		Course cr2 = new Course("2", "马克思");
		courses.add(cr2);
		
		ChildCourse cr3 = new ChildCourse();
		cr3.HaHa("3", "数学");
		courses.add(cr3);
		//以下会报错
//		courses.add("随便添加元素");
	}
	
	public void ForEach(){
		//由于泛型可以控制输入元素的类型, 因此元素在保存的就是Course类型, 
		//所以for each循环可以直接使用Course类型, 而不需要使用Object类型
		for(Course course:courses) {
			System.out.println(course.id + ":" + course.name);
		}
	}
}
package com.imooc.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//java迭代器
import java.util.Iterator;

/**
 * 备选课程类
 * @author admin
 *
 */
public class ListTest {
	//用于存放备选课程的List
	private List CourseToSelect;

	public List getCourseToSelect() {
		return CourseToSelect;
	}
 
	public void setCourseToSelect(List courseToSelect) {
		CourseToSelect = courseToSelect;
	}
	
	public ListTest(){
		this.CourseToSelect = new ArrayList();
	}
	//用于往CourseToSelect中添加备选课程
	public void testAdd() {
		Course cr1 = new Course("1", "数据结构");
		//调用List实现的add()方法, 用于将数据添加到集合中
		CourseToSelect.add(cr1);
		//将集合中的元素取出, 调用List的get()方法
		//由于存入集合的元素都是Object类型,引起取出的时候需要进行类型转换
		Course temp1 = (Course)CourseToSelect.get(0);
		System.out.println("第一次添加课程: " + temp1.getId() + ": " + temp1.getName());
		//测试List的add方法给指定位置添加
		Course cr2 = new Course("2", "网络知识");
		CourseToSelect.add(0, cr2);
		Course temp2 = (Course)CourseToSelect.get(0);
		System.out.println("第二次添加课程: " + temp2.getId() + ": " + temp2.getName());
		/**
		 * 添加数据时, 不指定位置则会在集合的尾部添加数据,指定位置的话指定的位置不能超过集合长度,
		 * 否则会报越界访问的错误
		 * 例如:
		 */
//		Course cr3 = new Course("3", "互联网+");
		//CourseToSelect.add(5, cr3); //这种情况运行时会报错
		/**
		 * 使用addAll()方法添加整个数组
		 * addAll(array)
		 * addAll(index, array)
		 */
		/**
		 * List集合,可以重复定义元素
		 * CourseToSelect.add(cr1);
		 * Course temp0 = CourseToSelect.get(2);
		 * 此时下标为2的元素就变成了temp0, 而temp3和temp4就会顺序往后移一位
		 */
		//创建Course类型数组
		Course[] course1 = {new Course("3", "离散数学"), new Course("4", "Java教程")};
		//调用Arrays.asList()方法, 将数组转换成集合
		CourseToSelect.addAll(Arrays.asList(course1));
		Course temp3 = (Course)CourseToSelect.get(2);
		Course temp4 = (Course)CourseToSelect.get(3);
		System.out.println("第三次添加课程: " + temp3.getId() + ": " + temp3.getName() + "; " + temp4.getId() + ": " + temp4.getName());
		Course[] course2 = {new Course("5", "大学语文"), new Course("6", "大学体育")};
		CourseToSelect.addAll(2, Arrays.asList(course2));
		Course temp5 = (Course)CourseToSelect.get(2);
		Course temp6 = (Course)CourseToSelect.get(3);
		System.out.println("第四次添加课程: " + temp5.getId() + ": " + temp5.getName() + "; " + temp6.getId() + ": " + temp6.getName());
	}
	//使用for遍历集合
	public void getByFor() {
		//获取集合长度
		int size = CourseToSelect.size();
		System.out.println("通过for循环遍历课程集合:");
		for(int i = 0; i <= size - 1; i++) {
			Course cr = (Course)CourseToSelect.get(i);
			System.out.println("课程: " + cr.getId() + ": " + cr.getName());
		}
	}
	//使用迭代器遍历集合,是collection接口的一个方法
	public void getByIterator() {
		//创建本集合的迭代器
		Iterator it = CourseToSelect.iterator();
		System.out.println("通过迭代器遍历的课程: ");
		while(it.hasNext()) {
			Course cr = (Course)it.next();
			System.out.println("课程: " + cr.getId() + ": " + cr.getName());
		}
	}
	//通过for each遍历
	public void getForEach(){
		System.out.println("通过for each遍历课程");
		for(Object obj:CourseToSelect) {
			Course cr = (Course)obj;
			System.out.println("课程: " + cr.getId() + ": " + cr.getName());
		}
	}
	//修改集合元素
	public void modify(){
		CourseToSelect.set(4, new Course("7", "思修"));
	}
	//删除元素
	public void remove(){
		//获取元素object
//		Course cr = (Course)CourseToSelect.get(4);
//		CourseToSelect.remove(cr);
//		CourseToSelect.remove(4);
		//使用removeAll
		Course[] course = {(Course)CourseToSelect.get(4), (Course)CourseToSelect.get(5)};
		CourseToSelect.removeAll(Arrays.asList(course));
		getForEach();
	}
	public static void main(String[] args){
		ListTest lt = new ListTest();
		lt.testAdd();
		lt.getByFor();
		lt.getByIterator();
		lt.getForEach();
		lt.modify();
		lt.getForEach();
		lt.remove();
	}
}
package com.imooc.collection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class SetTest {
	
	public List
       
       
         CourseList; private Scanner console; public Student student; public SetTest(){ this.CourseList = new ArrayList 
        
          (); console = new Scanner(System.in); } public static void main(String[] args) { // TODO Auto-generated method stub SetTest st = new SetTest(); Scanner input = new Scanner(System.in); //创建学生对象 Student student = new Student("1", "小明"); // System.out.println("欢迎" + student.getName() + "同学选课: "); //添加课程, 并且遍历显示课程 st.testAdd(); // st.courseForEach(); //获取选择课程的编号 //set类型对象添加是无序添加, 并且不会添加重复对象, 只保留第一次添加的对象 for(int i = 0; i < 3; i++) { System.out.println("请选则课程编号: "); String selectId = input.next(); for(Course cr:st.CourseList) { if(selectId.equals(cr.id)) { student.course.add(cr); } } } st.ForEachSet(student); //测试contains方法 // st.testContains(); // st.createStudentAndSelectCours(); st.setContains(); } //使用List的Contains方法判断类中是否有某元素 public void testContains(){ // Course course = CourseList.get(0); // System.out.println("获取到课程: " + course.getName()); // System.out.println("课程中是否包含课程: " + course.getName() + " " + CourseList.contains(course)); // Course course2 = new Course(course.id, course.name); // System.out.println("课程中是否包含课程: " + course2.name + " " + CourseList.contains(course2));//会报错, 因此需要重写equals方法 while(true) { System.out.println("请输入课程名称:"); String name = console.next(); Course course2 = new Course(); course2.name = name; System.out.println("新创建课程:" + course2.name); System.out.println("备选课程中是否包含课程:" + course2.name + ", " + CourseList.contains(course2)); if (CourseList.contains(course2)) System.out.println("课程:" + course2.name + "的索引位置为:" + CourseList.indexOf(course2)); } } // 创建学生对象并选课 public void createStudentAndSelectCours() { //创建一个学生对象 student = new Student("1", "小明"); System.out.println("欢迎学生:" + student.name + "选课!"); //创建一个Scanner对象,用来接收从键盘输入的课程ID Scanner console = new Scanner(System.in); for (int i = 0; i < 3; i++) { System.out.println("请输入课程ID"); String courseId = console.next(); for (Course cr : CourseList) { if(cr.id.equals(courseId)) { student.course.add(cr); } } } SetTest st = new SetTest(); st.ForEachSet(student); } //使用set的Contains方法 public void setContains(){ // 提示输入课程名称 System.out.println("请输入学生已选的课程名称:"); String name = console.next(); // 创建一个新的课程对象,ID和名称,与course对象完全一样 Course course2 = new Course(); course2.name = name; System.out.println("新创建课程:" + course2.name); System.out.println("备选课程中是否包含课程:" + course2.name + ", " + student.course.contains(course2)); } //遍历选择的课程 public void ForEachSet(Student student){ System.out.println("共选择了" + student.course.size() + "门课"); for(Course sc:student.course) { System.out.println("选择了课程: " + sc.id + ": " + sc.name); } } //添加课程 public void testAdd(){ Course cr1 = new Course("1", "高等数学"); Course cr2 = new Course("2", "线性代数"); Course cr3 = new Course("3", "概率统计"); Course cr4 = new Course("4", "算法导论"); Course cr5 = new Course("5", "数据结构"); Course cr6 = new Course("6", "思想政治"); Course[] crs = {cr1, cr2, cr3, cr4, cr5, cr6}; CourseList.addAll(Arrays.asList(crs)); } public void courseForEach(){ System.out.println("从以下课程中选择: "); for(Course course:CourseList){ System.out.println(course.id + ": " + course.name); } } } package com.imooc.collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; public class testMap { /* * 创建Map类型的学生对象 */ public Map 
         
           students; /* * 创建构造器,初始化students */ public testMap(){ this.students = new HashMap 
          
            (); } public static void main(String[] args) { // TODO Auto-generated method stub testMap te = new testMap(); te.add(); te.testEntrySet(); te.testContainsValue(); } //添加学生 public void add(){ Scanner input = new Scanner(System.in); int i = 1; while(i <= 3) { System.out.println("输入学生id: "); String id = input.next(); //判断id是否被占用 Student exit = students.get(id); if(exit != null) { System.out.println("该id已经被占用!"); continue; } else { System.out.println("请输入学生姓名:"); String name = input.next(); //将学生信息存入HashMap对象 students.put(id, new Student(id, name)); System.out.println(name + " 学生添加成功!"); i++; } } } //遍历输出学生对象 public void outPut(){ System.out.println("共有" + students.size() + "名学生."); //使用keySet方法查出所有下标 Set 
           
             key = students.keySet(); for(String k:key){ Student st = students.get(k); System.out.println("学生: " + st.getId() + ": " + st.getName()); } } //删除指定下标的学生 public void remove(){ Scanner input = new Scanner(System.in); while(true) { System.out.println("输入要删除的学生编号:"); String id = input.next(); Student one = students.get(id); if(one == null) { System.out.println("学生不存在"); continue; } else { //进行删除 students.remove(id); System.out.println("成功删除学生: " + one.getName()); break; } } } //使用entrySet遍历Map键值对 public void testEntrySet(){ //Entry类带有泛型, 泛型类型与定义Map时的类型相同, 因此需要对Entry进行泛型操作 Set 
             
             
               > all = students.entrySet(); for(Entry 
              
                stu:all){ //使用Entry的getKey()方法可直接获取下标 System.out.println("取得键: " + stu.getKey()); //使用Entry的getValue()方法获得键值 System.out.println("学生为: " + stu.getValue().getName()); } } /*修改Map对象 * 使用put方法, 传入已经存在的下标值 */ public void modify(){ Scanner input = new Scanner(System.in); while(true) { System.out.println("输入要修改的学生的key值"); String id = input.next(); Student exit = students.get(id); if(exit == null) { System.out.println("该学生不存在!"); continue; } else { System.out.println("修改学生姓名为: "); String name = input.next(); students.put(id, new Student(id, name)); System.out.println("成功修改学生姓名为: " + name); break; } } } //查询学生是否存在 public void testContainsKey() { System.out.println("输入要查询的学生id: "); Scanner input = new Scanner(System.in); String id = input.next(); System.out.println(students.get(id).name); System.out.println(students.containsKey(id)); } public void testContainsValue(){ System.out.println("输入要查询的学生姓名: "); Scanner input = new Scanner(System.in); String name = input.next(); System.out.println(students.containsValue(new Student(null, name))); } } 
               
              
             
            
           
          
         
       
      
      
     
     
    
    
   
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值