java集合类入门

List集合类

以一个学生选课系统为例,实现集合类List的增删改查

首先定义课程类Course,有属性id和name

然后实例化List类,使用ArrayList()方法

public List coursesToSelect;
public ListTest(){
    this.coursesToSelect = new ArrayList();
}

增(四种方法)

Course cr1 = new Course("1 ","数据结构");
Course[] course = {new Course("3 ","离散数学"),
                   new Course("4 ","汇编语言"),
                };
coursesToSelect.add(cr1);
coursesToSelect.add(0,cr1);
coursesToSelect.addAll(Arrays.asList(course));
coursesToSelect.addAll(2,Arrays.asList(course2));

//对象放入集合后自动成object类型,所以取得时要重新强制转化成源类型
        Course temp = (Course)coursesToSelect.get(0);
        System.out.println("添加的课程是:" + temp.id + temp.name);

查(三种方法)

//循环遍历
    public void testGet(){
        System.out.println("有如下课程可选:(普通循环实现)");
        int size = coursesToSelect.size();
        for(int i = 0 ; i < size ; i++){
            Course cr = (Course)coursesToSelect.get(i);
            System.out.println("课程是:" + cr.id + "." + cr.name);
        }
    }
    //迭代器遍历
    public void testIterator(){
        Iterator it = coursesToSelect.iterator();
        System.out.println("有如下课程可选:(迭代器实现)");
        while(it.hasNext()){
            Course cr = (Course)it.next();
            System.out.println("课程是:" + cr.id + "." + cr.name);
        }   
    }
    //for each循环遍历
    public void testForEach(){
        System.out.println("有如下课程可选:(for each实现)");
        for(Object obj : coursesToSelect){
            Course cr = (Course)obj;
            System.out.println("课程是:" + cr.id + "." + cr.name);
        }
    }

coursesToSelect.set(4,new Course("7","毛概"));

删(三种)

coursesToSelect.remove(cr);//第一种,删对象
coursesToSelect.remove(4);//第二种,删位置
coursesToSelect.removeAll(Arrays.asList(cr1));//第三种,删多个

判断是否包含某个元素

//contains()方法,若存在返回true,不存在返回false
//indexOf()方法,若存在返回元素的位置,若不存在返回-1

        if(coursesToSelect.contains(course2)){
            System.out.println("这个课程" + course2.name + "的索引位置为:" + coursesToSelect.indexOf(course2));
        }
//这里需要重写equal方法和hashCode方法
//为什么?因为contains方法 实际是调用equal方法 来比较的,如果不重写,只要是两个不同的对象,都会返回false
//Course类里重写
    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return true;
        }
        if(obj == null){
            return false;
        }
        if(!(obj instanceof Course)){
            return false;
        }
        Course course = (Course)obj;
        if(this.name == null){
            if(course.name == null){
                return true;
            }
            else
                return false;

        }
        else{
            if(this.name.equals(course.name))
                return true;
            else
                return false;
        }
    }

泛型集合

实例化(List类–>ArrayList() 或者Set类–>HashSet()

public List<Course> courses;
//public Set<Course> courses;

public TestGeneric(){
    this.courses =  new ArrayList<Course>();
    //this.courses = new HashSet<Course>();
}

//不能添加除Course之外的其他类型
Course cr1 = new Course("1 ","语文");
courses.add(cr1);
//courses.add("nishisshui");报错

//遍历时不用类型转换
for(Course cr : courses){
    System.out.println("课程是:" + cr.id + "." + cr.name);
}

//泛型可以使用子类型
public class ChildCourse extends Course {
}
ChildCourse ccr = new ChildCourse();
courses.add(ccr);
//泛型不能使用基本类型,需用包装类
//List<int> list = new ArrayList<int>();报错
List<Integer> list = new ArrayList<Integer>();
list.add(1);//添加成功,自动类型转换

排序(sort()方法)

List<Integer> integerList = new ArrayList<Integer>();
Collections.sort(integerList);
随机产生10个字符串(长度小于10),字符可重复,字符串不可重复
(课后小作业)

    List<String> stringList = new ArrayList<String>();
    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        Random random = new Random();
        for(int i = 0 ; i < 10 ; i++){
            String st = new String("");
            int a = random.nextInt(9)+1;
            for(int j = 0 ; j < a ; j++){
                char c = chars.charAt(random.nextInt(62));
                st = st + c;
                //System.out.println(st);
            }
            while(stringList.contains(st) == false){
                System.out.println("将要添加字符串:" + st);
                stringList.add(st);
            }
        }
        System.out.println("******排序前*****");
        for(String string : stringList)
            System.out.println("元素" + string);
 Collections.sort(stringList);
        System.out.println("******排序后*****");
        for(String string : stringList)
            System.out.println("元素" + string);

给集合(Student序列)排序(两种方法)

第一种:Comparable接口:默认比较规则
必须实现compareTo()方法
这里写图片描述

List<Student> studentList = new ArrayList<Student>();
Collections.sort(studentList);
//这里Student类必须实现Comparable接口
public class Student implements Comparable<Student> {
        ...

    @Override
    public int compareTo(Student o) {
        // 默认使用学生的id排序
        return this.id.compareTo(o.id);
    }
}

第二种:Comparator接口:临时比较规则
必须实现compare()方法
这里写图片描述

List<Student> studentList = new ArrayList<Student>();
Collections.sort(studentList, new StudentComparator());
public class StudentComparator implements Comparator<Student> {
        ...
    @Override
    public int compare(Student o1, Student o2) {
        // 这里规定按照学生姓名排序
        return o1.name.compareTo(o2.name);
    }
}

Map集合类

以一个学生选课系统为例,实现Map集合类的增删改查

首先定义学生类Student,有属性id和name

然后实例化Map类,是一组键值对

public Map<String,Student> students;
public MapTest(){
    this.students = new HashMap<String,Student>();
}

//首先判断要添加的id是否存在,用get方法,存在返回 键值,不存在返回 空对象
Student st = students.get(ID);
//若id不重复,用put方法,添加
students.put(ID,newStudent);

//返回所有键值
Set<String> keySet = students.keySet();
System.out.println("总共有" + students.size() + "个学生");
for(String stuId : keySet){
    Student st = students.get(stuId);
    if(st != null)
        System.out.println("学生" + st.name);
}
//返回所有键值对
Set<Entry<String,Student>> entryset = students.entrySet();
for(Entry<String,Student> entry : entryset){
    System.out.println("键值:" + entry.getKey());
    System.out.println("对应的值:" + entry.getValue().name);
}   

students.remove(ID);

Student newStudent = new Student(newId,newName);
students.put(stuId, newStudent);

是否存在某个键值

if(students.containsKey(id)){
    System.out.println("对应的姓名是:" + students.get(id).name);
}
if(students.containsValue(new Student(null,name))){
    System.out.println("学生存在!:" + name);
}
//因为使用了contains,这里也需要重写equal方法和hashCode方法
//在Student类中重写
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值