`
cainiaoyu
  • 浏览: 20776 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

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

阅读更多
为了方便的对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各种功能集合和工具.rar

    Collections是操作集合对象的工具类 Objects是操作引用数据类型对象的工具类 Arrays的常用方法 普通排序 Arrays.sort(int[] a) Arrays.sort(int[] a, int fromIndex, int toIndex) 并行排序:JDK1.8新增 Arrays....

    java集合类演示源码

    Java平台提供了一个全新的集合框架,框架的核心为Collection、List(列表)、Set(集合)和Map...为了方便用户使用,Java平台还提供了Collections和Arrays工具类。collection.rar分别对上述内容进行详细讲解演示。

    java常用工具类的使用

    在Java开发类库中,提供了很多工具类,我们即将学习最常见的工具类,比如对日期的操作,对集合的操作等。具体更多的工具类,请参考JavaDoc文档。 2. java.util.Date类 Date类包装了毫秒值,毫秒值表示自1970年1月1...

    Collections集合工具类排序.docx

    数组有工具类Arrays,集合也有一个工具类Collections,这里练习一下集合工具类的排序方法,顺便过一下sort排序方法,比较器。 sort方法 sort(List&lt;T&gt; list):根据其元素的natural ordering对指定的列表进行排序。 ...

    Java基础最全笔记文档

    6. 集合工具类Collections、Map集合、集合嵌套、不可变集合 7. Stream流、异常处理 8. Logback日志框架、阶段项目 9. File、方法递归、字符集、IO流(一) 10. IO流(二) 11. 多线程 12. 网络编程 13. 单元测试、...

    Java基础知识点总结.docx

    Collections--集合工具类 83 Arrays—数组对象工具类 84 增强for循环 85 可变参数(...) 86 枚举:关键字 enum 86 自动拆装箱 86 泛型 87 &lt;java.lang&gt;System 89 &lt;java.lang&gt;Runtime 90 &lt;java.lang&gt;Math 90 &lt;java....

    Java集合类——前言

    工具类(Iterator迭代器、Enumeration枚举类、Arrays和Collections) 这个图乱的一批o_o … emmmm大致可以看出,上面有三巨头,即Iterator、Collection、Map(虚线框是接口,实线框是类),Java的集合类主要就是由...

    Java开发详解.zip

    031314_【第13章:Java类集】_集合工具类:Collections笔记.pdf 031315_【第13章:Java类集】_Stack类笔记.pdf 031316_【第13章:Java类集】_属性类:Properties笔记.pdf 031317_〖第13章:Java类集〗_范例讲解:一...

    观看韩顺平Java的 所做的笔记 到互斥锁 其中里面有我很多心得 老手可以用来复习 新手可以用学习 也可以当做参考 来做笔记

    ArrayList 底层结构和源码分析 Vector 底层结构和源码剖析 LinkedList 底层结构 ArrayList 和 LinkedList 比较 Set 接口和常用方法 Map 接口和常用方法 总结-开发中如何选择集合实现类(记住) Collections工具类 泛型...

    java8源码-guava-demo:番石榴演示

    不过具体是否应用依据项目而定,在Java8环境下,Java8同样提供一些工具类和函数式接口与guava有 重叠的功能,类似Java8有Collections,Arrays,Optional,StringUtils,Stream,Consumer等。所以在Java中没有所需要的 工具...

    java抢票软件源码-interview:java面试题整理

    中的排序工具有哪些;有什么区别? Collections.sort算法调用的是合并排序。 Arrays.sort() 采用了2种排序算法 -- 基本类型数据使用快速排序法,对象数组使用归并排序。 String,StringBuffer和StringBuilder的区别;...

    JSON-lib包

    JSON-lib包是一个beans,collections,maps,java arrays 和XML和JSON互相转换的包。在本例中,我们将使用JSONObject类创建JSONObject对象,然后我们打印这些对象的值。

    KiteReport_20210515115933.rar

    · 支持所有.Net数据源类型,包括DataSets,DataViews,Collections,Arrays和类实现IEnumerable, IList or IListSource,一张报表支持多个数据源 · 使用GDI+实现:渐变填充,透明度,定制形状等 · 支持C#/VB.NET脚本,也...

Global site tag (gtag.js) - Google Analytics