package collection;
import character.Hero;
import java.util.ArrayList;
public class TestCollection {
public static void main(String[] args){
ArrayList heros = new ArrayList();
for(int i=0;i<5;i++){
heros.add(new Hero("hero: "+i));
}
System.out.println(heros);
Hero specialHero = new Hero("specila hero");
heros.add(2,specialHero);//在指定位置增加
System.out.println(heros);
//contains判定是否是同一对象,名称相同但不同对象输出false
System.out.println(heros.contains(new Hero("hero: 1")));
System.out.println(heros.contains(specialHero));//true
//get获取指定位置的对象,注意边界
System.out.println(heros.get(5));
//System.out.println(heros.get(6));
//indexOf判断一个对象在ArrayList所处位置
System.out.println(heros.indexOf(specialHero));
System.out.println(heros.indexOf(new Hero("hero: 1")));//返回-1
//remove可以根据对象和下标进行删除
//heros.remove(specialHero);
heros.remove(2);
System.out.println(heros);
//set用于替换指定位置的对象
heros.add(new Hero("special hero"));
System.out.println(heros);
heros.set(5,new Hero("hero: 5"));
System.out.println(heros);
//size获取list大小
System.out.println(heros.size());//6
//toArray可以吧一个ArrayList对象转换为数组
Hero[] hs = (Hero[])heros.toArray(new Hero[]{});
System.out.println("数组:"+hs);
ArrayList anotherHeros = new ArrayList();
anotherHeros.add(new Hero("hero a"));
anotherHeros.add(new Hero("hero b"));
heros.addAll(anotherHeros);//整个数组添加
System.out.println(heros);
System.out.println(anotherHeros);
anotherHeros.clear();//清空
System.out.println(anotherHeros);
}
}
java基础——ArrayList基本操作
最新推荐文章于 2024-02-01 10:24:43 发布