Int数组转化为List列表,以便于排序操作

Effective Java 中的代码,摘录于此:
package com.vefan.common.util;

import java.util.AbstractList;
import java.util.Collections;
import java.util.List;

/**
 * 人生若只如初见,何事秋风悲画扇;等闲变却故人心,却道故人心易变。
 * */
public class IntList
{
	/**
	 * 把Int数组转化为List列表,以便于排序操作
	 * */
	static List intArrayAsList(final int[] a){
		if(a == null)
			throw new NullPointerException();
		
		return new AbstractList(){

			@Override
			public Object get(int index)
			{
				return new Integer(a[index]);
			}

			@Override
			public int size()
			{
				return a.length;
			}
			
			//排序所用到的方法
			public Object set(int index, Object o){
				int oldVal = a[index];
				a[index] = ((Integer)o).intValue();
				return new Integer(oldVal);
			}
			
		};
	}
	
	public static void main(String[] args){
		int[] a = new int[5];
		for(int i=0; i<a.length; i++){
			a[i] = i;
		}
		
		List lt = intArrayAsList(a);
		System.out.println(lt);
		Collections.shuffle(lt);
		System.out.println(lt);
		Collections.sort(lt);
		
	}
}

你可能感兴趣的:(java)