ArrayList

ArrayList集合  本质上相当于长度可变数组,所以用法有相似之处。

package collection;

import java.util.ArrayList;

class Dog{

private String name;

private String sex;

public Dog() {

super();

}

public Dog(String name, String sex) {

super();

this.name = name;

this.sex = sex;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

}

public class ArrayLi {

public static void main(String[] args) {

ArrayList list = new ArrayList();

Dog dog1 = new Dog("jerry","female");

Dog dog2 =new Dog("tom","male");

list.add(dog1);//添加对象

list.add(0, dog2);

list.add(new Dog("lucy","female"));

System.out.println("删除之前有"+list.size()+"条狗狗");

Dog dog[] = new Dog[3] ;

dog[0]= (Dog)list.get(0);//获取对象

dog[1] = (Dog)list.get(1);

dog[2] = (Dog)list.get(2);

for (Dog dg : dog) {

System.out.println("我的名字是"+dg.getName());

}

Dog  g = (Dog)list.remove(0);

System.out.println("删除的狗狗是"+g.getName());

System.out.println(list.remove(dog2));//因为dog1已被删除,所以结果为false

System.out.println(list.remove(dog1));//true

System.out.println("删除之后有"+list.size()+"条狗狗");

for(int i = 0;i

    Dog dg = (Dog)list.get(i);//获取对象

    System.out.println("我的名字是"+dg.getName());

}

}

}

ArrayList_第1张图片

                                         参考于在线api(Collection接口)

ArrayList_第2张图片

 package collection;

import java.util.ArrayList;

import java.util.Collection;

import java.util.Iterator;

public class Demo1 {

public static void main(String[] args) {

Collection col = new ArrayList();

Collection col2 = new ArrayList();

//Collection为接口所以col调用的所有方法

//皆为ArrayList类中的实现Collection接口中的方法

System.out.println(col);//结果:[]

//col自动调了col.toString()方法进行了转换

//所以输出的不是地址

System.out.println("------------------");

col.add("tom");

col.add("tom");

System.out.println(col); //结果:[tom, tom]

col2.addAll(col);

System.out.println(col2); //结果:[tom, tom]

col2.clear();

System.out.println("------------------");

System.out.println(col2);//结果:[]

System.out.println(col.contains("tom"));//结果:true

System.out.println(col.equals(col2));//结果:false

col2.addAll(col);

System.out.println(col.equals("tom"));//结果:false

System.out.println(col.equals(col2));//结果:true

Object[] a = col.toArray();

System.out.println(a);//地址

System.out.println(a[0]);//tom

System.out.println(a[1]);//tom

Iterator ite = col.iterator();

while(ite.hasNext()){

System.out.print(ite.next());//tomtom

}

int size = col.size();

System.out.println(size);//2

}

}

你可能感兴趣的:(ArrayList)