Java集合框架Example-2

来源:互联网 发布:杭州掌玩网络猫老大 编辑:程序博客网 时间:2024/05/16 10:25

课程修改

public void testModify(){coursesToSelect.set(4,new Course("7","ITPS"));}
删除
/* * 删除List中的元素 */public void testRemove(){Course cr=(Course) coursesToSelect.get(4);coursesToSelect.remove(cr);System.out.println("成功删除");testForEach();}/* * 删除2 */public void testRemove1(){System.out.println("即将删除序列为2的课程");coursesToSelect.remove(2);testForEach();}/*<pre name="code" class="java">public class TestGeneric {/** 带有泛型---Course的List类型属性*/public List<Course> courses;public TestGeneric(){this.courses=new ArrayList<Course>();//()意思是调用构造方法}/* * 测试增加 */public void testAdd(){Course cr1=new Course("1","English");courses.add(cr1);Course cr2=new Course("2","German");courses.add(cr2);}/* * 测试循环遍历 */public void testForEach(){for(Course cr:courses){System.out.println(cr.id+" "+cr.name);}}public static void main(String[] args) {// TODO Auto-generated method stubTestGeneric Tg=new TestGeneric();Tg.testAdd();Tg.testForEach();}
/* * 删除4,5位上的元素 */<span style="white-space:pre"></span>public void testRemoveAll(){<span style="white-space:pre"></span>System.out.println("即将删除序列为4,5的课程");<span style="white-space:pre"></span>Course[] courses={(Course) coursesToSelect.get(4),(Course) coursesToSelect.get(5)};<span style="white-space:pre"></span>coursesToSelect.removeAll(Arrays.asList(courses));<span style="white-space:pre"></span>System.out.println("成功删除课程");<span style="white-space:pre"></span>testForEach();<span style="white-space:pre"></span>}

泛型

集合中的元素可以是任意类型的对象(对象的引用)。如果把某个对象放入集合,则会忽略他的类型,而把他当作Object处理

泛型则是规定了某个集合只可以存放特定类型的对象,会在编译期间进行类型检查,可以直接按指定类型获取集合元素。

public class TestGeneric {/** 带有泛型---Course的List类型属性*/public List<Course> courses;public TestGeneric(){this.courses=new ArrayList<Course>();//()意思是调用构造方法}/* * 测试增加 */public void testAdd(){Course cr1=new Course("1","English");courses.add(cr1);Course cr2=new Course("2","German");courses.add(cr2);}/* * 测试循环遍历 */public void testForEach(){for(Course cr:courses){System.out.println(cr.id+" "+cr.name);}}public static void main(String[] args) {TestGeneric Tg=new TestGeneric();Tg.testAdd();Tg.testForEach();}

泛型集合中除了能存入泛型类型还能存入泛型子类型。泛型集合中的限定类型不能使用基本数据类型,只能引用类型。可以通过使用包装类限定允许存入的基本类型数据。int-integer;long-Long; boolean-Boolean

/* * 基本类型包装类 */public void testBasicType(){List<Integer> list=new ArrayList<Integer>();list.add(1);System.out.println("基本类型必须使用包装类"+list.get(0));}





0 0
原创粉丝点击