Java中两个集合工具类:Collections和Arrays_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java中两个集合工具类:Collections和Arrays

Java中两个集合工具类:Collections和Arrays

 2014/4/7 21:51:18  cainiaoyu  程序员俱乐部  我要评论(0)
  • 摘要:为了方便的对Array对象、Collection对象进行操作,Java中提供了Arrays类和Collections类对其进行操作。Collections:是集合对象的工具类,提供了操作集合的工具方法Arrays:是数组的工具类,提供了对数组的工具方法其中Arrays和Collections中所有的方法都为静态的,不需要创建对象,直接使用类名调用即可。Collections比较常用的方法:1,为List集合进行排序Collections.sort()codeimportjava.util
  • 标签:工具 Java
为了方便的对Array对象、Collection对象进行操作,Java中提供了Arrays类和Collections类对其进行操作。
Collections:是集合对象的工具类,提供了操作集合的工具方法
Arrays:是数组的工具类,提供了对数组的工具方法
其中Arrays和Collections中所有的方法都为静态的,不需要创建对象,直接使用类名调用即可。
Collections比较常用的方法:
1,为List集合进行排序Collections.sort()
code
import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Iterator;

class student implements Comparable {

private int age;

private String name;

public student(String name ,int age) {

this.name = name;

this.age = age;

}

public String getname() {

return name;

}

public int getage(){

return age;

}

public int compareTo(Object o){

if(!(o instanceof student))

throw new RuntimeException("不是学生");

student s = (student) o;

System.out.println(this.name+"-----"+s.name);

int num = new Integer(this.age).compareTo(s.age);

if(num == 0)

return this.name.compareTo(s.name);

return num;

}

}

public class Test{

public static void main(String[] args) {

ArrayList<student> al= new ArrayList<student>();

al.add(new student("zhangsan", 11));

al.add(new student("lisi", 12));

al.add(new student("wangwu", 11));

//Collections.sort(al);如果存储的对象实现了comparable接口可以按照compareTo方法来排序

Collections.sort(al, new myComparator());//也可以根据自己比较器所定义的方法来排序

Iterator<student> it = al.iterator();

while (it.hasNext()) {

student s = it.next();

System.out.println(s.getname()+"!!"+s.getage());

}

}

}

class myComparator implements Comparator{

public int compare(Object o, Object o1) {

if(!(o instanceof student) || !(o1 instanceof student))

throw new RuntimeException("不是学生");

student s = (student) o;

student s1 = (student) o1;

System.out.println(s.getname()+"-----"+s1.getname());

int num = new Integer(s.getage()).compareTo(s1.getage());

if(num == 0)

return s.getname().compareTo(s1.getname());

return num;

}

}
2,返回集合(List和Set)中的最大最小值:Collections.max和Collections.min

code
import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Iterator;

import java.util.List;

class student implements Comparable {

private int age;

private String name;

public student(String name ,int age) {

this.name = name;

this.age = age;

}

public String getname() {

return name;

}

public int getage(){

return age;

}

public int compareTo(Object o){

if(!(o instanceof student))

throw new RuntimeException("不是学生");

student s = (student) o;

System.out.println(this.name+"-----"+s.name);

int num = new Integer(this.age).compareTo(s.age);

if(num == 0)

return this.name.compareTo(s.name);

return num;

}

}

public class Test{

public static void main(String[] args) {

List<student> al= new ArrayList<student>();

al.add(new student("zhangsan", 11));

al.add(new student("lisi", 12));

al.add(new student("wangwu", 11));

//student student = Collections.max(al, new myComparator());//按照自己定义的比较器内的方法来返回最大最小值

//student s1 = Collections.min(al,new myComparator());

student student = Collections.max(al);//按compareTo方法来返回最大最小值,返回的是具体存储的类型。

student s1 = Collections.min(al);

System.out.println(student.getname()+"+++++"+student.getage());

System.out.println(s1.getname()+"+++++"+s1.getage());

}

}

class myComparator implements Comparator{

public int compare(Object o, Object o1) {

if(!(o instanceof student) || !(o1 instanceof student))

throw new RuntimeException("不是学生");

student s = (student) o;

student s1 = (student) o1;

System.out.println(s.getname()+"-----"+s1.getname());

int num = new Integer(s.getage()).compareTo(s1.getage());

if(num == 0)

return s.getname().compareTo(s1.getname());

return num;

}

}
3,对List集合进行二分查找:Collections.binarySearch,在此方法调用之前,需要先进行升序排序Collections.sort()。查询到返回位置否则返回-(index)-1。

code
import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Iterator;

import java.util.List;

class student implements Comparable<student> {

private int age;

private String name;

public student(String name ,int age) {

this.name = name;

this.age = age;

}

public String getname() {

return name;

}

public int getage(){

return age;

}

public int compareTo(student o){

student s = (student) o;

System.out.println(this.name+"-----"+s.name);

int num = new Integer(this.age).compareTo(s.age);

if(num == 0)

return this.name.compareTo(s.name);

return num;

}

}

public class Test {

public static void main(String[] args) {

List<student> al= new ArrayList<student>();

al.add(new student("zhangsan", 11));

al.add(new student("lisi", 12));

al.add(new student("wangwu", 11));

Collections.sort(al);

//System.out.println(Collections.binarySearch(al, new student("zhangsan", 11)));//按自然顺序进行二分查找,返回1;

System.out.println(Collections.binarySearch(al, new student("zhangsan", 11),new myComparator()));//按比较器定义的顺序

}

}

class myComparator implements Comparator<student>{

public int compare(student o, student o1) {

student s = (student) o;

student s1 = (student) o1;

System.out.println(s.getname()+"-----"+s1.getname());

int num = new Integer(s.getage()).compareTo(s1.getage());

if(num == 0)

return s.getname().compareTo(s1.getname());

return num;

}

}
4,反转集合内元素的顺序,reverse(反转List的顺序),reverseOrder(强行反转比较器的顺序)返回的是一个比较器
code

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.Iterator;

import java.util.List;

class student implements Comparable<student> {

private int age;

private String name;

public student(String name ,int age) {

this.name = name;

this.age = age;

}

public String getname() {

return name;

}

public int getage(){

return age;

}

public int compareTo(student o){

student s = (student) o;

System.out.println(this.name+"-----"+s.name);

int num = new Integer(this.age).compareTo(s.age);

if(num == 0)

return this.name.compareTo(s.name);

return num;

}

}


public class Test{

public static void main(String[] args) {

List<student> al= new ArrayList<student>();

al.add(new student("zhangsan", 11));

al.add(new student("lisi", 12));

al.add(new student("wangwu", 11));

//Collections.sort(al,Collections.reverseOrder());//反转compareTo方法的顺序

//Collections.reverse(al);//针对List的反转方法

Collections.sort(al,Collections.reverseOrder(new myComparator()));//反转compare方法的顺序

Iterator<student> it = al.iterator();

while (it.hasNext()) {

student s = it.next();

System.out.println(s.getname()+"!!"+s.getage());

}

}

}

class myComparator implements Comparator<student>{

public int compare(student o, student o1) {

student s = (student) o;

student s1 = (student) o1;

System.out.println(s.getname()+"-----"+s1.getname());

int num = new Integer(s.getage()).compareTo(s1.getage());

if(num == 0)

return s.getname().compareTo(s1.getname());

return num;

}

}
5,将集合类变成线程安全的(synchronizedCollection(Collection<T> c)、synchronizedList(List<T> list)、synchronizedMap(Map<K,V> m)、synchronizedSet(Set<T> s))

源码:

   public static <T> List<T> synchronizedList(List<T> list) {

return (list instanceof RandomAccess ?

                new SynchronizedRandomAccessList<T>(list) :

                new SynchronizedList<T>(list));

    }

    static <T> List<T> synchronizedList(List<T> list, Object mutex) {

return (list instanceof RandomAccess ?

                new SynchronizedRandomAccessList<T>(list, mutex) :

                new SynchronizedList<T>(list, mutex));

    }

    /**

     * @serial include

     */
static class SynchronizedList<E>
extends SynchronizedCollection<E>

implements List<E> {

        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) {

    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<E>(list.subList(fromIndex, toIndex),

                                            mutex);

            }

        }

通过定义一个内部类,并重写了List所有方法(调用初始化所传入的List所实现的方法),同时用相同的对象锁来保证同步
Arrays常用的方法:
Arrays.binarySearch//二分查找
Arrays.copyOf //复制
Arrays.copyOfRange//复制部分
Arrays.sort//排序
Arrays.fill//填充
Arrays.toString//字符串返回
Arrays.hashCode//哈希值
Arrays.asList//将数组转为List
code


public class Test {

public static void main(String[] args) {

String arr[] = {"aaa","ccc","bb"};

List<String> list = Arrays.asList(arr);

System.out.println(list.contains("bb"));

int arr1[] = {1,2,3};

List<int[]> list1 = Arrays.asList(arr1);

System.out.println(arr1);

}

}
注:
1,将数组变成List,可以使用对集合的操作方法来操作数组,但是不可以对集合使用增删的操作(数组长度是固定的),否则会抛出UnsupportedOperationException异常
2,如果数组中的元素都为对象,变成集合时,会直接将这些元素作为集合的元素;如果数组中的元素为基本类型,变成集合时,将以整体为集合的一个元素。  
引申:Collection接口中有一个toArray方法,将集合转为数组

code
public class Test{

public static void main(String[] args) {

ArrayList<String> al = new ArrayList<String>();

al.add("aaa");

al.add("ccc");

al.add("dd");

String s[] = al.toArray(new String[al.size()]);

System.out.println(Arrays.toString(s));

}

}
注:
1,指定类型数组的大小小于集合的size()时,toArray方法会内部新建一个数组。当长度大于或等于集合的Size时,则直接使用传递进来的数组。
2,集合变成数组可以限定对集合中元素的操作。(数组长度不可变)

jdk1.5新特性
Collection就有了一个父接口Iterable
该接口的出现封装了iterator方法,并提供了一个增强型的for循环
格式:
for(元素类型 变量 :数组或者Collection集合)
{
}
code
public class Test {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("aaa");
al.add("ccc");
al.add("dd");
for (String string : al) {
System.out.println(string);
}
}
}
注:使用增强性for循环只能获取集合元素,不能对集合中的元素进行操作,迭代器在遍历中还可以进行remove操作


增强for循环和传统for循环区别:
增强for循环,使用时,必须要有被遍历的目标
而且只能遍历数组和Collection集合,简化了迭代
传统for循环,使用更加普遍
注意:遍历数组还是使用传统for循环,这样可以通过指针对数组中的元素进行操作
可变参数
在指定数据类型的后面加上三个点,其实就是一个数组类型的参数
以前定义一个int[]类型 参数,调用必须要定义好一个数组,再往里传递
而现在定义一个int…类型的参数,调用者,直接往该函数里传递元素即可
在运行时,自动会将这些实际参数封装到一个该类型的数组中。
注意:如果函数上有多个参数,可变参数一定要定义在参数列表最后边,否则编译失败
code
public class Test{
public static void main(String[] args) {
show(2,2,3,4);
}
public static  void show(int... arr) {
System.out.println(Arrays.toString(arr));
}
}
上一篇: Java-io小结 下一篇: 没有下一篇了!
发表评论
用户名: 匿名