跟汤老师学Java笔记:练习2:ArrayList

跟汤老师学Java笔记:

完成:第一遍

1.练习2:ArrayList
提示用户输入5名学生的学号和成绩,创建Student对象,然后放到ArrayList集合中
1.遍历集合,删除学号为2的学生
2.不遍历集合,删除学号为3的学生
3.不遍历集合,判断集合中是否包含学号为3的学生

/**
 * 提示用户输入5名学生的学号和成绩,创建Student对象,然后放到ArrayList集合中
 * 1.遍历集合,删除学号为2的学生
 * 2.不遍历集合,删除学号为3的学生
 * 3.不遍历集合,判断集合中是否包含学号为3的学生
 */
package season13;

import java.util.ArrayList;
import java.util.Scanner;


public class TestArrayList2 {

	public static void main(String[] args) {
		
		Scanner input = new Scanner(System.in);
		
		ArrayList<Student> arrayList = new ArrayList<Student>();
		
		for (int i = 1; i <= 5; i++) {
			System.out.println("请输入第"+i+"名学生信息");
			System.out.print("请输入学号:");
			int nid = input.nextInt();
			System.out.print("请输入成绩:");
			int score = input.nextInt();
			
			Student student = new Student();
			student.setNid(nid);
			student.setScore(score);
			//向集合添加student对象
			arrayList.add(student);
		}
        
		//遍历,删除学号为2的学生
		for (int i = 0; i <arrayList.size(); i++) {		
			Student s = arrayList.get(i);
			if(s.getNid()==2){
				arrayList.remove(i);
			}
		}
		
		//不遍历集合,删除学号为3的学生
		Student stu = new Student();
		stu.setNid(3);
		//重写Student的equals()方法
		arrayList.remove(stu);
		
		boolean isContain = arrayList.contains(stu);
		System.out.println(isContain);
		
		System.out.println(arrayList);
		
		
	}
}
class Student{
	
	private int nid;
	private int score;
	public int getNid() {
		return nid;
	}
	public void setNid(int nid) {
		this.nid = nid;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	
	
	
	@Override
	public int hashCode() {
	
		return super.hashCode();
	}
	@Override
	public boolean equals(Object obj) {
		Student stu=(Student)obj;
		if(nid == stu.nid){
			return true;
		}
		return false;
	
	}
	@Override
	public String toString() {
		return "Student [nid=" + nid + ", score=" + score + "]";
	}
}

你可能感兴趣的:(Java之集合之List集合,java)