测试
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList array=new ArrayList();
//或者ArrayList array=new ArrayList<>();
array.add("天地");
array.add("任我");
array.add(1,"广阔");
array.add(3,"傲游");
//array.add(5,"索引越界报错");
System.out.println(array);
}
}
运行结果
求长度:数组.length,String类.length()方法,ArrayList集合.size()
测试
import java.util.ArrayList;
public class ArrayListDemo02 {
public static void main(String[] args) {
ArrayList array=new ArrayList();
array.add("天地");
array.add("广阔");
array.add("疏又何妨");
array.add("狂有何妨");
array.remove("广阔");
array.remove(0);//删索引为0 即删天地
array.set(1,"虽千万人吾往矣");
System.out.println(array.get(1));
System.out.println(array);
}
}
运行结果
使用ArrayList存储学生对象并存储学生类
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
测试
import java.util.ArrayList;
public class ArrayListDemo03 {
public static void main(String[] args) {
ArrayList array=new ArrayList();
Student s1=new Student("唐三",18);
Student s2=new Student("小舞",17);
Student s3=new Student("比比东",50);
array.add(s1);
array.add(s2);
array.add(s3);
for (int i = 0; i
运行结果
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)