import java.util.*;
public class ArrayListdemo{
public static void main(String[] args){
//构造一个指定容量为10的数组
ArrayList<Student> strArr=new ArrayList<Student>(10);
strArr.add(new Student("张三",23,123456,"男"));
strArr.add(new Student("张三",23,123456,"男"));
strArr.add(new Student("李四",23,123456,"男"));
strArr.add(new Student("王五",23,123456,"男"));
strArr.add(new Student("张三",23,123456,"男"));
//返回当前元素的数量;
int x=strArr.size();
System.out.println(x);
//get(int index) 返回此列表中指定位置上的元素。
Student stu=strArr.get(3);
System.out.println(stu.getName());
//add(int index, E element) 将指定的元素插入此列表中的指定位置。
strArr.add(5,new Student("jack",23,123456,"男"));
strArr.add(6,new Student("jodan",23,123456,"男"));
//在4位置插入一个元素,4后面的元素都向后移动一位
strArr.add(4,new Student("King",23,123456,"男"));
Student stu1=strArr.get(6);
System.out.println(stu1.getName());
}
}
/**
自定义学生类
**/
class Student{
private String name;
private int age ;
private int stuNumber;
private String gender;
//无参构造器
public Student(){
}
//有参构造器
public Student(String name,int age,int stuNumber,String gender){
this.name=name;
this.age =age;
this.stuNumber=stuNumber;
this.gender=gender;
}
public String getName(){
return name;
}
public int getAge(){
return age ;
}
public int getStuNumber(){
return stuNumber;
}
public String getGender(){
return gender;
}
public void setName(String n){
name=n;
}
public void setAge(int a){
age=a;
}
public void setStuNumber(int s){
stuNumber=s;
}
public void setGender(String g){
gender=g;
}
}
运行结果:
5
王五
jack