集合(一):Collection

 

一:Collection与Collections的区别

1.java.util.Collection是一个集合接口(集合类的一个顶级接口)。它提供了对集合对象进行基本操作的通用接口方法。Collection接口在Java类库中有很多具体的实现。Collection接口的意义是为各种具体的集合提供最大化的统一操作方式,其直接继承接口有List与Set。如下:

public interface List<E> extends Collection<E> {}
public interface Set<E> extends Collection<E> {}

2.java.util.Collections是一个包装类(工具类/帮助类)。它包含有各种关系集合操作的静态多态方法。此类不能实例化(至于为什么不能实例化,参考源码),就像一个工具类,用于对集合中元素进行排序,搜索以及线程安全等各种操作,服务于Java的Collection框架。

public class Collections {
    // Suppresses default constructor, ensuring non-instantiability.
    private Collections() {
    }
}

 

二:接下来看看集合中对象容器的分类:

然后简单了解下Collection中的主要方法:

1.定义一个Person类:

package com.berg.se.bean;

public class Person {

	private String name;
	private int age;
    /**
	 * 提供 构造方法,get set方法,hashCode 与 equals方法。
	 * */
	
}

 2.测试:

public class Test01Collection {

	@Test
	public void test1(){
		//推荐使用泛型。
		Collection<Person> collection = new ArrayList<Person>();
		collection.add( new Person("Berg",22) );
		collection.add( new Person("JavaSe",21));
		
		System.out.println( "size: "+ collection.size() );
		
		//collection.contains() :如果此 collection 包含指定的元素,则返回 true。
		Person pe = new Person("Berg",22);
		//这里需要Person类中重写 hashCode()方法与wquals()方法。
		boolean flag = collection.contains(pe);  
		System.out.println( " 该元素是否存在 : " + flag );
		
		//addAll():
		Collection<Person> collection1 = new ArrayList<Person>();
		collection1.add( new Person("BergBerg",22) );
		collection1.add( new Person("JavaSe-Berg",21));
		
		collection1.addAll(collection);
		System.out.println(  collection1.size() );
		
		/**
		 * 在Collection中无法获取指定的元素,但可以遍历所有的元素
		 * 1.使用增强型for循环遍历所有元素
		 * 2.使用Iterator迭代器
		 * 	2.1 获取迭代器对象:调用Collection的iterator()方法。获取Iterator接口的对象。
		 * 	2.2调用Iterator接口的方法进行迭代。
		 */
		//1.使用增强型for循环遍历所有元素
		for (Person person : collection1) {
			System.out.println( person );
		}
		System.out.println( "*********Iterator***********\n\n");
		//2.使用Iterator迭代器
		Iterator<Person> iterator = collection1.iterator();
		//hasNext() : 表示如果仍有元素可迭代 ,则返回true。
		while( iterator.hasNext() ){
			Person p = iterator.next();
			System.out.println(  p ) ;
		}
		//以下将会抛出NoSuchElementException
		//Person p = iterator.next(); // 因为没有元素可以继续迭代了。
	}
	
	@Test
	public void test2(){
		//注意List是实现Collection接口的
        List list = new ArrayList();
        int array[] = { 9,5,7,8,3,1,4,2,6 };
        for (int i = 0; i < array.length; i++) {
            list.add(new Integer(array[i]));
        }
        Collections.sort(list);  // 排序: 默认按升序进行排序。
        for (int i = 0; i < array.length; i++) {
            System.out.print(list.get(i) + "  ");
        }
        // 结果:23.0 111.0 112.0 231.0 456.0
	}
}

 

转载于:https://my.oschina.net/gently/blog/680691

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值