Java基础十四

1 对象数组

  • 示例:
package com.xuweiwei;

/**
 * 学生类
 */
public class Student {
    private String name;
    private Integer age;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.xuweiwei;

/**
 * 我有5个学生,请把这5个学生的信息存储到数组中,并遍历数组,获取到每一个学生的信息
 */
public class ObjectArrayDemo {
    public static void main(String[] args) {
        Student s1 = new Student("a",8);
        Student s2 = new Student("b",9);
        Student s3 = new Student("c",10);
        Student s4 = new Student("d",11);
        Student s5 = new Student("e",12);

        Student[] students = {s1,s2,s3,s4,s5};

        for (int i = 0; i < students.length; i++) {
            Student s = students[i];
            System.out.println(s);
        }

    }
}

2 集合

2.1 集合的概述

2.1.1 为什么出现集合?

  • 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。

2.1.2 数组和集合类同时容器,有什么不同?

  • 数组虽然也可以存储对象,但是长度是固定的;集合的长度是可以变化的。
  • 数组中可以存储基本类型的数据,但是集合只能存储对象。

2.1.3 集合类的特点

  • ①集合只能存储对象。
  • ②集合的长度是可以变化的。
  • ③集合可以存储不同类型的对象。

2.2 Collection集合

2.2.1 Collection集合的概述

猜你喜欢

转载自www.cnblogs.com/xuweiweiwoaini/p/9320638.html