Clloection接口 与List接口

collection接口:

collection是单列集合接口的根接口,该接口中又包含了多个集合接口,collection接口提供了很多操作集合的方法,比如添加元素的方法,删除元素的方法,修改元素的方法等。

collection接口的常用方法
boolean add(E e)                                            将指定的对象添加到集合当中            
bolean remove(object o)            删除集合中的指定对象
bolean isEmpty()            判断集合中是否包含元素
int size()            获取集合中元素的个数
object [] toArray           返回包含集合中所有元素的数组
iterator<E> itterator           返回集合的迭代器,用于遍历该集合2018-05-20
扫描二维码关注公众号,回复: 950108 查看本文章
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;



public class collectionTest {
	public static void main(String[] args) {
		Collection  c=new ArrayList();//实例化实现了collection接口的类
		
		//向集合中添加数据
		c.add("A");
		c.add("B");
		c.add("C");
		//判断集合中是否存在数据
		System.out.println(c.isEmpty());
		System.out.println(c.size());//获取集合长度
		System.out.println("集合中元素为");
		Iterator it=c.iterator();//获取集合迭代器对象
		while(it.hasNext()){//判断集合中是否有下一个元素
			String s =(String) it.next();
			System.out.println(s);
		}
		
	}

}

 List接口:

List 接口继承了collection接口,List集合中允许出现重复的元素

而且存储在该集合的元素是有序的。

List 接口常用实现类有ArrayList类与LinkedList类

add(int index,object obj)                                                          向集合的index索引处添加obj对象               
  remove(int index)                            移除index索引处的集合对象
set(int index,object obj)                   修改index索引处的对象
get(int index)                   获取index索引出的集合对象
indexof(object obj)                   获取对象obj在集合中第一次出现的索引值
lastIndexof(object obj)                    获取对象obj在集合中最后一次出现的索引值   
方法名称     说明

        ArryayList集合的使用:

    Java中数值一旦创建其长度就不可改变,为了解决这个问题,集合框架定义了ArryaList类

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Collection  ls=new ArrayList ();
        ls.add("a");
        ls.add("b");
        ls.add("c");
        ls.add("d");
        
        System.out.println("a的索引为"+((ArrayList) ls).indexOf("a"));
        System.out.println("a的索引为"+((ArrayList) ls).lastIndexOf("a"));
        System.out.println("..........集合的元素的内容.........");
//        for(int i=0;i<ls.size();i++){
//         String s=(String) ((ArrayList) ls).get(i);
//         System.out.println(s);
//
//    }
        Iterator it=ls.iterator();
        while(it.hasNext()){
            String s =(String) it.next();
            System.out.println(s);
        }
}

LinkedlList集合的使用:

        方法名称                    说明
 object getFirst()    获取集合中的第一个元素
 object getLast()  获取结合中的最后一个元素
 void addFirst(E e)  将指定元素添加到集合的开头
void addLalt(E a)  将指定元素添加到集合的结尾

  

ArryayList集合和LinkedlList集合的区别:

ArryayList集合是实现了动态数组数据结构的集合,LinkedlList集合是实现了链表数据结构的集合。对于遍历集合元素操作,ArryayList集合效率优于LinkedlList集合

,对于增加和删除元素的操作,LinkedlList集合效率优于ArryayList集合。

猜你喜欢

转载自www.cnblogs.com/hurriediy/p/9063215.html