Arraylist
创建集合
package eight.list.arraylist; import java.util.ArrayList; import java.util.List; public class Student { public static void main(String[] args) { //创建集合 //List aa = new ArrayList(); ArrayList aa = new ArrayList(); aa.add("a"); aa.add(123); aa.add(true); System.out.println(aa); //System.out.println(aa.toString());//打印对象的引用会默认调用tostring方法 } } 真题练习
package eight.list.arraylist; import java.util.ArrayList; import java.util.Arrays; public class Test { public static void main(String[] args) { Dog d1 = new Dog("花花","中华田园犬"); Dog d2 = new Dog("龙龙","泰迪"); Dog d3 = new Dog("壮壮","哈士奇"); Dog d4 = new Dog("迪迪","拉布拉多"); ArrayList list = new ArrayList(); list.add(d1); list.add(d2); list.add(d3); list.add(d4); System.out.println(list); System.out.println(list.size());//size方法,打印集合元素个数 //删除指定狗狗 for (int i = 0; i < list.size(); i++) { if (list.contains(d1)){//contains是否包含 list.remove(i);//remove删除 break; }else{ System.out.println("没有指定狗狗"); } } System.out.println(list); }}
package eight.list.arraylist; public class Dog { private String name; private String trye; public Dog(String name, String trye) { this.name = name; this.trye = trye; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ", trye='" + trye + '\'' + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTrye() { return trye; } public void setTrye(String trye) { this.trye = trye; } public void eat(){} public void run(){} }
泛型集合 在编译时增加类型检查
package eight.list.arraylist; //泛型集合 在编译时增加类型检查 import java.util.ArrayList; import java.util.List; public class GenericTest { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>();//加泛型把错误提到编译期 list.add("qqyumidi"); list.add("corn"); //list.add(100);//Integer类型转换异常 for (int i = 0; i < list.size(); i++) { //Object o1 = list.get(); String object = (String) list.get(i);//Object转换String System.out.println(object); //System.out.println(list.get(i)); } } }标签:String,List,Arraylist,list,Dog,add,集合,public,name From: https://blog.csdn.net/Anyway_01/article/details/136683042