黑马程序员---Collections工具类

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

 

如果我们存储的元素有可能重复,而且需要快速频繁查询的话,我们就选用ArrayList集合进行存储。

但是我们又需要对其中元素进行排序,这就用到了Collections工具类。

Collections工具类中有专门对List集合的元素进行排序的方法。

public static <? extends Comparable<? super T>> void sort(List<T> list);
public static <T> void sort(List<T> list, Comparator<? super T> comparator);


下面演示:

import java.util.*;
class CollectionsDemo 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		ArrayList<String> al = new ArrayList<String>();
		al.add("aaa");
		al.add("bbc");
		al.add("lapla");
		al.add("Los");
		al.add("agaless");
		sop(al);

		//Collections.sort(al);
		Collections.sort(al,new strLengthComparator());
		sop(al);
	}
}

class strLengthComparator implements Comparator<String>
{
	public int compare(String s1, String s2)
	{
		int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(0==num)
		{
			return s1.compareTo(s2);
		}
		return num;
	}
}


获取Collection中最大元素:

public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> collection);

public static T max(Collection<? extends T> collection, Comparator<? super T> comparator);

下面演示:

import java.util.*;
class CollectionsDemo 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("aaa");
		al.add("bbc");
		al.add("zapla");
		al.add("Los");
		al.add("agaless");
		sop(al);

		Collections.sort(al);
		sop(al);

		String max = Collections.max(al);
		sop(max);

		//Collections.sort(al,new strLengthComparator());
		//sop(al);

		//String max = Collections.max(al,new strLengthComparator());
		//sop(max);
	}
}

class strLengthComparator implements Comparator<String>
{
	public int compare(String s1, String s2)
	{
		int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(0==num)
		{
			return s1.compareTo(s2);
		}
		return num;
	}
}


使用二分查找法搜索指定列表,以获得指定对象。为什么搜索的类型是List呢?因为二分查找涉及到脚标。

但是你知道,但凡用binarySearch,必须是有序集合。

public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key);  //进行此调用之前,必须通过sort(List)方法进行升序排序。

public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> comparator);  //进行此调用之前,必须通过sort(List, Comparator)方法进行升序排序。

 下面演示:(如果找不到,返回-插入点-1)

import java.util.*;
class CollectionsDemo 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("aaa");
		al.add("bbc");
		al.add("zapla");
		al.add("Los");
		al.add("agaless");

		//String max = Collections.max(al);
		//sop(max);

		//String max = Collections.max(al,new strLengthComparator());
		//sop(max);

		//Collections.sort(al);
		//sop(al);
		//int index = Collections.binarySearch(al,"aaa");
		//sop(index);
		
		Collections.sort(al,new strLengthComparator());
		sop(al);
		int index = Collections.binarySearch(al,"bbc",new strLengthComparator());
		sop(index);
	}
}

class strLengthComparator implements Comparator<String>
{
	public int compare(String s1, String s2)
	{
		int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(0==num)
		{
			return s1.compareTo(s2);
		}
		return num;
	}
}

 

二分查找原理:

import java.util.*;
class CollectionsDemo 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("aaa");
		al.add("bbc");
		al.add("zapla");
		al.add("Los");
		al.add("agaless");

		//String max = Collections.max(al);
		//sop(max);

		//String max = Collections.max(al,new strLengthComparator());
		//sop(max);

		//Collections.sort(al);
		//sop(al);
		//int index = Collections.binarySearch(al,"aaa");
		//int index = halfSearch(al,"aaaa");
		//sop(index);
		
		Collections.sort(al,new strLengthComparator());
		sop(al);
		//int index = Collections.binarySearch(al,"aaaa",new strLengthComparator());
		int index = halfSearch2(al,"aaaa",new strLengthComparator());
		sop(index);
	}

	//二分查找原理:
	public static int halfSearch(List<String> list, String key)
	{
		int min,max,mid;
		min = 0;
		max = list.size()-1;
		
		while(min<=max)
		{
			mid = (min+max)>>1; // /2
			String str = list.get(mid);
			int num = str.compareTo(key);
			if(num>0)
			{
				max = mid-1;
			}
			else if(num<0)
			{
				min = mid+1;
			}
			else
				return mid;
		}
		return -min-1;
	}

	public static int halfSearch2(List<String> list, String key, Comparator<String> comparator)
	{
		int min,max,mid;
		min = 0;
		max = list.size()-1;
		
		while(min<=max)
		{
			mid = (min+max)>>1; // /2
			String str = list.get(mid);
			int num = comparator.compare(str,key);
			if(num>0)
			{
				max = mid-1;
			}
			else if(num<0)
			{
				min = mid+1;
			}
			else
				return mid;
		}
		return -min-1;
	}
}

class strLengthComparator implements Comparator<String>
{
	public int compare(String s1, String s2)
	{
		int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(0==num)
		{
			return s1.compareTo(s2);
		}
		return num;
	}
}


使用指定元素替换指定列表中的所有元素。

public static <T> void fill(List<? super T> list, T obj);

import java.util.*;
class CollectionsDemo1 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("aaa");
		al.add("bbc");
		al.add("zapla");
		al.add("Los");
		al.add("agaless");
		sop(al);

		//Collections.fill(al,"qq");
		//sop(al);

		partFill(al,0,3,"qq");
		sop(al);
	}

	/*练习:fill方法可以将list集合中所有元素替换成制定元素,
	将集合中部分元素替换成制定元素*/
	public static <T> void partFill(List<T> list,int start,int end,T key)
	{
		List<T> newList = list.subList(start,end);
		Collections.fill(newList,key);
	}
}


static
<T> boolean
replaceAll(List<T> list, T oldVal, T newVal)
          使用另一个值替换列表中出现的所有某一指定值。
static voidreverse(List<?> list)
          反转指定列表中元素的顺序。

演示:

import java.util.*;
class CollectionsDemo2 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("a");
		al.add("cc");
		al.add("bbb");
		al.add("dddk");
		al.add("agaless");
		sop(al);

		Collections.replaceAll(al,"cc","aa");
		sop(al);

		Collections.reverse(al);
		sop(al);
	}
}


static
<T> Comparator<T>
reverseOrder()
          返回一个比较器,它强行逆转实现了 Comparable 接口的对象 collection 的自然顺序
static
<T> Comparator<T>
reverseOrder(Comparator<T> cmp)
          返回一个比较器,它强行逆转指定比较器的顺序。

演示:

import java.util.*;
class CollectionsDemo3 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		//Collections.reverseOrder()倒转自然顺序
		//Collections.reverseOrder(new Comparator())倒转比较器顺序
		TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder(new strLenComparator()));
		ts.add("a");
		ts.add("cc");
		ts.add("bbb");
		ts.add("dddkf");
		ts.add("agaless");
		sop(ts);
	}
}

class strLenComparator implements Comparator<String>
{
	public int compare(String s1, String s2)
	{
		int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
		if(0==num)
		{
			return s1.compareTo(s2);
		}
		return num;
	}
}


 

static
<T> List<T>
synchronizedList(List<T> list)
          返回指定列表支持的同步(线程安全的)列表。

我们都知道ArrayList是线程不同步的,在add的同时不能remove,必须等add以后再remove,remove完再add,如果几个线程一起执行就会报错。

我们只要将不安全的List传到public static <T> List<T> synchronizedList(List<T> list)这个方法中,就返回给你一个安全的List。

其实她的内部原理就是复写了add、remove等方法,调用了原来的add、remove方法并把他们封在synchronized(锁)代码块里。

我们可以看一下源码:

    public static <T> List<T> synchronizedList(List<T> list) {
        return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<>(list) :
                new SynchronizedList<>(list));
    }

    static <T> List<T> synchronizedList(List<T> list, Object mutex) {
        return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<>(list, mutex) :
                new SynchronizedList<>(list, mutex));
    }

    /**
     * @serial include
     */
    static class SynchronizedList<E>
        extends SynchronizedCollection<E>
        implements List<E> {
        private static final long serialVersionUID = -7754090372962971524L;

        final List<E> list;

        SynchronizedList(List<E> list) {
            super(list);
            this.list = list;
        }
        SynchronizedList(List<E> list, Object mutex) {
            super(list, mutex);
            this.list = list;
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            synchronized (mutex) {return list.equals(o);}
        }
        public int hashCode() {
            synchronized (mutex) {return list.hashCode();}
        }

        public E get(int index) {
            synchronized (mutex) {return list.get(index);}
        }
        public E set(int index, E element) {
            synchronized (mutex) {return list.set(index, element);}
        }
        public void add(int index, E element) {
            synchronized (mutex) {list.add(index, element);}
        }
        public E remove(int index) {
            synchronized (mutex) {return list.remove(index);}
        }

        public int indexOf(Object o) {
            synchronized (mutex) {return list.indexOf(o);}
        }
        public int lastIndexOf(Object o) {
            synchronized (mutex) {return list.lastIndexOf(o);}
        }

        public boolean addAll(int index, Collection<? extends E> c) {
            synchronized (mutex) {return list.addAll(index, c);}
        }

        public ListIterator<E> listIterator() {
            return list.listIterator(); // Must be manually synched by user
        }

        public ListIterator<E> listIterator(int index) {
            return list.listIterator(index); // Must be manually synched by user
        }

        public List<E> subList(int fromIndex, int toIndex) {
            synchronized (mutex) {
                return new SynchronizedList<>(list.subList(fromIndex, toIndex),
                                            mutex);
            }
        }


 

static voidreverse(List<?> list)
          反转指定列表中元素的顺序。

reverse这个方法其实就是调用了swap方法:

static voidswap(List<?> list, int i, int j)
          在指定列表的指定位置处交换元素。

swap这个方法之所以要暴露出来,就是可以让你交换List集合里面两个元素的位置。

swap方法演示:

import java.util.*;
class CollectionsDemo2 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("a");
		al.add("cc");
		al.add("bbb");
		al.add("dddk");
		al.add("agaless");
		sop(al);
		
		Collections.swap(al,0,2);
		sop(al);
	}
}


 

static voidshuffle(List<?> list)
          使用默认随机源对指定列表进行置换。

对指定列表中的元素的位置进行随机的置换

演示:

import java.util.*;
class CollectionsDemo2 
{
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}

	public static void main(String[] args) 
	{
		List<String> al = new ArrayList<String>();
		al.add("a");
		al.add("cc");
		al.add("bbb");
		al.add("dddk");
		al.add("agaless");
		sop(al);
		
		Collections.shuffle(al);
		sop(al);
	}
}

结果每次都不一样:


这个方法存在的道理:

比方说扑克牌是一个类,一副扑克有54张牌,这54张牌相当于54个对象,这54个对象存放在一个集合中,

你新买的一副扑克一打开是有顺序的,但是你在玩的过程中需要洗牌,你调用这个方法一次就相当于洗一次牌。

 

 

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值