标签:修改 rate demo 删除元素 替换 数据类型 创建 列表 span
1:集合类,在java语言中的java.util包提供了一些集合类,这些集合类又被称作容器。
2:区别集合类和数组。(1)数组的长度是固定的,集合的长度是可变的。(2)数组是用来存放基本数据类型的,集合是用来存放对象的引用。
3 : 常用的集合有List集合,Set集合,Map集合。其中List集合和Set集合实现Collection接口。
4:Collection接口是层次结构中的根接口,构成Collection的单位,被称为元素。Collection接口通常不能直接使用,但是该接口提供了添加和删除元素的,管理数据的方法。由于List接口和Set接口都实现了Collection接口,因此这些方法对List集合和Set集合是通用的。
5:List集合是列表类型,以线性方式存储对象,因此可以通过对象的索引来操作对象。
6:List集合中的add(in index,Object obj)方法,用来向集合中的指定索引位置添加对象,集合的索引位置从0开始,其他对象的索引位置相对向后移动一位。
7:List集合中的set(int index,E element)方法用指定的元素替换列表中的指定位置的元素,返回以前在指定位置的元素。
案例如下,创建集合对象,并向集合中添加元素,通过Set方法修改集合中的元素,再通过add()方法向集合中添加元素,都是通过迭代器遍历集合元素的。
1 package com.ning; 2 3 import java.util.*; 4 5 /** 6 * 7 * @author biexiansheng 8 * 9 */ 10 public class Demo { 11 12 public static void main(String[] args) { 13 String a="A",b="B",c="C",d="D",e="E";//定义要插入集合的字符串对象 14 List<String> list=new LinkedList<String>();//创建List集合 15 list.add(a);//向集合中添加元素 16 list.add(b); 17 list.add(c); 18 Iterator<String> iter=list.iterator();//创建集合的迭代器 19 System.out.println("修改后 前集合 中的元素是:"); 20 while(iter.hasNext()){ 21 System.out.print(iter.next()+" "); 22 } 23 list.set(0,e);//将索引位置为0的对象修改为对象e 24 list.set(2,d);//将索引位置为2的对象修改为对象d 25 Iterator<String> it=list.iterator();//创建将集合对象修改后的迭代器对象 26 System.out.println(); 27 System.out.println("修改后的集合中的元素是:"); 28 while(it.hasNext()){//循环获取集合中的元素 29 System.out.print(it.next()+" "); 30 } 31 32 33 } 34 35 }
1 package com.ning; 2 3 import java.util.*; 4 5 public class Demo01 { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 String a="A",b="B",c="C",d="D",e="E",apple="apple";//要添加到集合中的对象 10 List<String> list=new ArrayList<String>();//创建List集合对象 11 list.add(a);//对象a的索引位置为0 12 list.add(apple);//对象apple的索引位置为1 13 list.add(b); 14 list.add(apple); 15 list.add(c); 16 list.add(apple); 17 list.add(d); 18 list.remove(1);//remove(int index)用于移除集合中指定索引位置的对象 19 System.out.println("ArrayList集合中的元素:"+list); 20 System.out.println("apple第一次出现的索引位置:"+list.indexOf(apple)); 21 System.out.println("apple最后一次出现的索引位置:"+list.lastIndexOf(apple)); 22 System.out.println("b第一次出现的索引位置:"+list.indexOf(b)); 23 System.out.println("b最后一次出现的索引位置:"+list.lastIndexOf(b)); 24 System.out.println("***********************************"); 25 //System.out.println("get()获得指定索引位置的对象:"+list.get(0)); 26 27 28 } 29 30 }
此两句话的使用结果对比显示:
list.remove(1);//remove(int index)用于移除集合中指定索引位置的对象
System.out.println("get()获得指定索引位置的对象:"+list.get(0));
至此,Collection接口下的List接口学习就差不多了,详细的还请自己下去参考资料,勤加练习,熟练应用和掌握。
java中集合类中Collection接口中的List接口的常用方法熟悉
标签:修改 rate demo 删除元素 替换 数据类型 创建 列表 span
原文地址:http://www.cnblogs.com/biehongli/p/5989290.html