使用Arraylist,记录一组student对象,实现遍历,查询,删除,并用Collections实现排序


import java.util.*;
import  java.util.ArrayList;
import  java.util.Collection;
public class student {
    private String name;
    private int age;
    public student(String name,int age)
    {
        this.age=age;
        this.name=name;

    }
    public static void main(String args[])
    {
        //构造放students的容器
        ArrayListstudents=new ArrayList<>();
        //给容器添加对象
        students.add(new student("Jone",25));
        students.add(new student("Alice",22));
        students.add(new student("Bob",19));
        //遍历
        printAll(students);
        //查询
        findname(students,"Bob");
        //删除
        removestudent(students,"Bob");
        //collections 排序
        Collections.sort(students,(S1,S2)->S1.age-S2.age);
        System.out.println("排序之后");
        printAll(students);

    }
    //遍历
    //
    public static void printAll(ArrayListstudents)
    {
        for(student a:students)
        {
            System.out.println(a.name);
        }
    }
    //查询
    public static student findname(ArrayListstudents,String searchname)
    {
        for(student a:students)
        {
            if(a.name.equals(searchname))
            {
                return a;
            }
        }
        return null;
    }
    public static void removestudent(ArrayListstudents,String removename)
    {
        student a=findname(students,removename);
        if(a!=null)
        {
            students.remove(a);
        }
    }

  }



你可能感兴趣的:(java,开发语言)