Java集合与泛型(一)

 

Java集合与泛型(一)

 

1、如上图在集合中的两大接口为:CollectionMap

 

2Collection的子接口有三个分别为:List(列表),Queue(队列),Set

这里只对最常用的做一下介绍。其中几个比较重要的几个实现类为:ArrayListLinkedListVectorHashSetHashMapHashTable

List是有顺序的序列,并且允许添加重复的对象。

 

3ArrayList中常用的方法:

1)从它的命名就可以看出这个列表和数组有一定的关系,其实它的底层实现就是用数组实现的。区别就是数组长度不可变,而ArrayList长度是可变的。在效率上数组要比ArrayList快。

2ArrayList的常用方法和操作可分为:添加、删除、修改、比较、遍历几种。如下面的代码实例中包括了这些基本操作:

 

创建的people类:

public class PeopleDemo {
	private String name;
	private boolean sex;
	
	public PeopleDemo(String name, boolean sex) {
		super();
		this.name = name;
		this.sex = sex;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public boolean isSex() {
		return sex;
	}
	public void setSex(boolean sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		String str;
		if(this.isSex()){
			str = "男";
		}else{
			str = "女";
		}
		return this.getName()+"性别"+str;
	}
}

 基本操作方法:

public class CollectionDemo {
	
	private static List list;
	private static PeopleDemo pd1;
	private static PeopleDemo pd2;
	private static PeopleDemo pd3;
	private static PeopleDemo pd4;
	private static PeopleDemo pd5;
	private static PeopleDemo[] pds1;
	private static PeopleDemo[] pds2;
	
	public static void init(){
		list = new ArrayList();
		pd1 = new PeopleDemo("张三", true);	
		pd2 = new PeopleDemo("李四", true);
		pd3 = new PeopleDemo("小红", false);
		pd4 = new PeopleDemo("小毛", true);
		pd5 = new PeopleDemo("小刘", false);
		pds1 = new PeopleDemo[]{pd4,pd5};
		pds2 = new PeopleDemo[]{pd2,pd3};
	}
	
	public static void testAdd(){
		list.add(pd1);
		list.add(0, pd2);
		list.addAll(Arrays.asList(pds1));
		list.addAll(1, Arrays.asList(pds2));
		testIterator2(list);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		init();
		testAdd();
		testRemove();
		testSet();
		
		System.out.println(list.containsAll(Arrays.asList(pds1)));
		
	}
	
	public static void testIterator(List list){
		int lenth = list.size();
		Iterator iterator = list.iterator();
		while(iterator.hasNext()){
			PeopleDemo pd = (PeopleDemo) iterator.next();
			System.out.println(pd.toString());
		}
	}
	
	public static void testIterator2(List list){
		for(Object o : list){
			PeopleDemo pdd = (PeopleDemo) o;
			System.out.println(pdd.toString());
		}
		System.out.println("------------------------------");
	}

	public static void testRemove(){
		list.remove(2);
		testIterator2(list);
		list.remove(pd2);
		testIterator2(list);
		list.removeAll(Arrays.asList(pds2));
		testIterator2(list);
	}
	
	public static void testSet(){
		list.set(0, pd4);
		testIterator2(list);
	}
}

 这里需要说的一点是,在遍历集合类对象时使用foreach语句要比for语句简便。

 

 

猜你喜欢

转载自xq8866.iteye.com/blog/2309591