Java基础:集合
来源:互联网 发布:淘宝实木床 编辑:程序博客网 时间:2024/05/16 06:42
源代码下载:http://download.csdn.net/detail/zhoujing_0424/9239347
一. 集合概述
1. 集合类的由来
对象用于封装特有数据,对象多了就需要进行存储,如果对象的个数不确定,那么就用集合容器进行存储。集合是用于存储对象的容器。
2. 集合的概念
集合有时又称为容器,简单地说,它是一个对象,能将具有相同性质的多个元素汇聚成一个整体。集合被用于存储、获取、操纵和传输聚合的数据。
3. 集合与数组的区别
1)集合长度是可变的;数组长度固定的。
2)集合中只能存储对象;数组中既可以存储对象,又可以存储基本类型数据。
3)集合中存储的对象可以是任意类型的;数组中只能存储同一类型的对象。
二. 集合框架
集合容器因为内部结构不同,有很多具体的容器,不断的向上抽取,就形成了集合框架。
Java平台提供了一个全新的集合框架,框架的核心为Collection、List(列表)、Set(集合)和Map(映射),如上图所示。图中虚线框的为接口,实线框的为具体的实现类。集合类的框架为集合的实现者提供了大量的接口和抽象类,并对其中的某些机制给予了描述,例如,Iterator(迭代协议)。实现Comparable接口或Comparator接口,用户可以根据需要对集合中的元素进行排序。为了方便用户使用,Java平台还提供了Collections和Arrays两个静态工具类。下面就从集合框架中的两个基本的接口Collection和Map入手,对其分别进行深入说明。
三. Collection接口
Collection是集合继承树中最顶层的接口,几乎所有的Java集合框架成员都继承实现了Collection接口,或者与其有密切关系。Collection提供了关于集合的通用操作。Collection的常见方法:
1.添加
add(Object obj);
addAll(Collection c);
2.删除
remove(Object obj);
removeAll(Collection c);
void clear();
3.判断
boolean contains(Object obj);
boolean containsAll(Collection c);
boolean isEmpty();
4.获取
int size();
Iterator iterator();
//返回在此collection的元素上进行迭代的迭代器。该对象必须依赖于具体的容器,因为每一个容器的数据结构都不同,所以该迭代器对象是在容器中进行内部实现的。对于容器的使用者而言,具体的实现并不重要,只要通过容器获取到该实现的迭代器对象即可,也就是Iterator()方法。Iterator接口就是对所有的collection容器进行元素取出的公共接口。迭代器就是实现了Iterator接口的每一个容器内部的内部对象,Iterator降低容器和取出元素之间的耦合性。
5.其他
boolean retainAll(Collection c);//仅保留此 collection 中那些也包含在指定 collection 的元素
Object[] toArray();//返回包含此collection中所有元素的数组
List和Set接口都实现了Collection接口,两者的区别如下:
1)List:有序(存入和取出的顺序一致),元素都有索引(角标),元素允许重复。
2)Set:元素不能重复,无序。
下面分别对这两个接口进行演示讲解。
四. List接口(列表)
1.List特有的常见方法
List列表作为集合的一种,其主要特点在于其中的元素保持一定的顺序。List特有的常见方法:
(1)添加
void add(int index,E element); //在列表指定位置插入指定元素
void add(int index,Collection c);//将指定collection中的所有元素插入到列表的指定位置
(2)删除
E remove(int index);//删除列表中指定位置的元素
(3)修改
E set(int index,E element);//用指定元素替换列表中指定位置的元素
(4)获取
E get(int index);//获取列表指定位置的元素
int indexOf(Object o);//返回列表中指定元素第一次出现的索引,若没有则返回-1
int lastIndexOf(Object o);//返回列表中指定元素最后一次出现的索引,若没有则返回-1
List subList(int fromIndex,int toIndex);//返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图
ListIterator listIterator();//返回此列表中元素的列表迭代器,可以实现在迭代过程中对元素进行增删改查。ListIterator是列表迭代器,允许程序员按任一方向遍历列表、在迭代期间修改列表,并获得迭代器在当前列表中的位置
ListIterator listIterator(int index);//返回此列表中元素的列表迭代器,从指定位置开始
2.List常用的具体实现类
(1)Vector:内部是数组数据结构,是同步的,效率低,几乎不用。增删查询都很慢。
(2)ArrayList:内部是数组数据结构,是不同步的,效率高,替代了Vector。若需要线程安全则加锁,而不使用Vector。查询的速度快。
(3)LinkedList:内部是链表数据结构,是不同步的。增删元素的速度非常快。
package com.zj.list.demo;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.ListIterator;public class ListDemo { public static void main(String[] args) { List<String> list =new ArrayList<String>();// show(list); show2(list); } public static void show(List<String> list){ list.add("abc1"); list.add("abc2"); list.add("abc3"); System.out.println(list);// //插入元素// list.add(1, "abc5");// // //删除元素// list.remove(2);// //修改元素// list.set(1, "abc6"); //获取元素 System.out.println(list.get(2)); //获取子列表 System.out.println(list.subList(1, 2));//包含1位置的元素,不包含2位置的元素 System.out.println(list); } public static void show2(List<String> list){ list.add("abc1"); list.add("abc2"); list.add("abc3"); /*for(Iterator it=list.iterator();it.hasNext();){ System.out.println("next:"+it.next()); Object obj=it.next(); if(obj.equals("abc2")){ // 抛出java.util.ConcurrentModificationException //集合和迭代器同时操作元素,会导致迭代出问题,则抛出异常 //解决方法为:迭代的时候不集合,集合的时候不迭代 list.add("abc7"); } else{ System.out.println("next"+obj); } }*/ //可以使用Iterator的子接口ListIterator来完成在迭代中对元素进行更多的操作 //它可以实现在迭代过程中对元素的增删改查。注意:只有list集合具备该迭代功能。 for(ListIterator<String> it=list.listIterator();it.hasNext();){ Object obj=it.next(); if(obj.equals("abc2")){ it.add("abc7"); } } //list特有的取出方式 for(int index=0;index<list.size();index++){ System.out.println("get:"+list.get(index)); } }}
package com.zj.list.demo;import java.util.Enumeration;import java.util.Iterator;import java.util.Vector;public class VectorDemo { public static void main(String[] args){ Vector<String> v=new Vector<String>(); v.addElement("abc1"); v.addElement("abc2"); v.addElement("abc3"); v.addElement("abc4"); //枚举,与Iterator功能重复 for(Enumeration<String> en=v.elements();en.hasMoreElements();){ System.out.println("next element:"+en.nextElement()); } for(Iterator<String> it=v.iterator();it.hasNext();){ System.out.println("next:"+it.next()); } }}
package com.zj.list.demo;import java.util.ArrayList;import java.util.Iterator;import com.zj.bean.Person;public class ArrayListDemo { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList al=new ArrayList(); al.add(new Person("zhangsan",21)); al.add(new Person("lisi",22)); al.add(new Person("wangwu",23)); al.add(new Person("zhaoliu",24)); for(Iterator<Person> it=al.iterator();it.hasNext();){ //直接打印it.next(),打印的是类型加哈希值。必须进行强制转换,然后再打印 Person p=(Person)it.next();// System.out.println(p.getName()+":"+p.getAge()); } al.add(5);//等价于al.add(new Integer(5));当基本数据类型值赋给引用数据类型时,自动装箱;当引用数据类型和基本数据类型运算时自动拆箱 test2(); } /** * 练习:去除集合中重复的元素 */ public static void test2() { ArrayList al=new ArrayList();// al.add("abc1");// al.add("abc2");// al.add("abc3");// al.add("abc4");// al.add("abc1");// al.add("abc3");// al.add("abc3"); Person p=new Person("zhaoliu",27); al.add(new Person("zhangsan",21)); al.add(new Person("lisi",22)); al.add(p); al.add(new Person("zhaoliu",23)); al.add(new Person("wangwu",24)); al.add(new Person("wangwu",24)); al.add(p); System.out.println(al); al=getSingleElement(al); System.out.println(al); System.out.println(new Person("zhaoliu",27).equals(p)); System.out.println(al.remove(new Person("lisi",22)));//remove底层使用的也是equals()方法 System.out.println(al); } public static ArrayList getSingleElement(ArrayList al) { // TODO Auto-generated method stub //1.定义一个临时容器 ArrayList temp=new ArrayList(); //2.遍历al集合 for(Iterator it=al.iterator();it.hasNext();){ Object obj=it.next(); //3.判断被迭代的元素是否在temp中存在 if(!temp.contains(obj)) temp.add(obj);//contains()方法依据的是equals方法,所以重写Person中的equals()方法即可 } return temp; }}
package com.zj.list.demo;import java.util.Iterator;import java.util.LinkedList;public class LinkedListDemo { public static void main(String[] args) { show(); } public static void show() { LinkedList<String> link=new LinkedList<String>(); link.addFirst("abc1"); link.addFirst("abc2"); link.add("abc3"); link.add("abc4"); System.out.println(link);// System.out.println(link.getFirst());//获取第一个但是不删除,如果链表为空,则抛出NoSuchElementException// System.out.println(link.removeFirst());//获取第一个并删除,如果链表为空,则抛出NoSuchElementException// System.out.println(link);// // JDK1.6:// System.out.println(link.peekFirst());//获取第一个但是不删除,如果链表为空则返回null// System.out.println(link.pollFirst());//获取第一个并删除,如果链表为空则返回null// System.out.println(link); while(!link.isEmpty()){ System.out.println("removeFirst:"+link.removeFirst()); } for(Iterator<String> it=link.iterator();it.hasNext();){ System.out.println(it.next()); } }}
package com.zj.bean;public class Person implements Comparable{ private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int hashCode() {// System.out.println("hashcode:"+this); return name.hashCode()+age*39;//乘以一个数,保证哈希值唯一,减少equals()方法调用的次数,提高效率 } @Override public boolean equals(Object obj) {// System.out.println("equals:"+this); if(this==obj) return true;//如果是同一个对象则直接返回true,不用再比较name和age if(!(obj instanceof Person))//如果对象类型不相同,则抛出异常,也不用再比较 throw new ClassCastException("类型错误"); if(this.name.equals(((Person)obj).name) && this.age==((Person)obj).age) return true; else return false; } public String toString(){ return name+":"+age; } //Comparable接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。 @Override public int compareTo(Object o) { if(!(o instanceof Person)) throw new ClassCastException("类型错误"); Person p=(Person)o;// if(this.name.compareTo(p.name)>0)return 1;// else if(this.name.compareTo(p.name)==0){// if(this.age==p.age) return 0;// return (this.age>p.age)?1:-1;// }else return -1;// int temp=this.name.compareTo(p.name);// return temp==0?this.age-p.age:temp; int temp=p.name.compareTo(this.name); return temp==0?p.age-this.age:temp; }}
五.Set接口(集合)
Set集合是一种不包含重复元素的Collection,即Set的构造函数有一个约束条件,传入的Collection参数不能包含重复的元素。Set不保证元素的顺序,即为无序的。下面将介绍Set中的两个主要的实现类HashSet和TreeSet。
1.HashSet
内部数据结构是哈希表,是不同步的。如何保证该集合中元素的唯一性?
通过对象的hashCode和equals方法来判断唯一性。如果对象的hashCode值不相同,则不用判断equals方法,直接存储到哈希表中;如果hashCode值相同,则使用equals方法再次判断,若为true则视为相同元素,否则视为不同元素。
总结:ArrayList中的contains()方法,仅仅使用equals方法,HashSet则使用hashCode()和equals()方法。
2.TreeSet
可以对Set集合中的元素进行排序,是不同步的。如何保证集合中元素的唯一性,并保证一定的顺序性?
TreeSet对元素的排序方式一:
让元素自身具备比较功能,对象实现Comparable接口,通过对象的compareTo方法来判断大小。返回0,则为相同元素;若为正数则大于;若为负数则小于。
如果不按照对象中具备的自然顺序排序,或对象中不具备自然顺序,则可以使用TreeSet集合的第二种排序方式。
TreeSet对元素的排序方式二:
让集合自身具备比较功能,定义一个类实现Comparator接口,覆盖compare方法。将该类对象作为参数传递给TreeSet集合的构造函数。
package com.zj.set.demo;import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedHashSet;import com.zj.bean.Person;public class HashSetDemo { public static void main(String[] args){// HashSet hs=new HashSet();// // hs.add("haha");//不保证有序// hs.add("xixi");// hs.add("hehe");// hs.add("heihei");// hs.add("hehe");//不允许重复,保证唯一// hs.add("hehe");// String s;// for(Iterator it=hs.iterator();it.hasNext();){// System.out.println(it.next());// } test(); test2(); } public static void test2() { //LinkedHashSet保证按元素插入顺序进行迭代 HashSet hs=new LinkedHashSet(); hs.add("haha"); hs.add("xixi"); hs.add("hehe"); hs.add("heihei"); hs.add("hehe");//不允许重复,保证唯一 hs.add("hehe"); for(Iterator it=hs.iterator();it.hasNext();){ System.out.println(it.next()); } } /** * 往HashSet中存储Person对象,若姓名和年龄一样则视为同一个人. * HashSet集合数据结构是哈希表,所以存储元素的时候,使用元素的hashcode方法来确定位置; * 如果位置相同,再通过equals方法来确定元素是否相同。 */ public static void test() { HashSet hs=new HashSet(); Person p=new Person("zhaoliu",27); //HashSet中不允许重复,判断使用hashCode()和equals()方法 hs.add(new Person("zhangsan",21)); hs.add(new Person("lisi",22)); hs.add(p); hs.add(new Person("zhaoliu",23)); hs.add(new Person("wangwu",24)); hs.add(new Person("wangwu",24)); hs.add(p); for (Iterator it = hs.iterator(); it.hasNext();) { Person p1=(Person)it.next(); System.out.println(p1.getName()+":"+p1.getAge()); } }}
package com.zj.set.demo;import java.util.Comparator;import java.util.Iterator;import java.util.TreeSet;import com.zj.bean.Person;public class TreeSetDemo { public static void main(String[] args){// test1();// test2(); test3(); } /** * 使TreeSet按元素的存入顺序遍历元素,实现有序存储 */ public static void test3() { // TODO Auto-generated method stub Comparator comparator=new ComparatorByLength(); TreeSet ts=new TreeSet(comparator); ts.add("ab"); ts.add("hcdfd"); ts.add("abz"); ts.add("zfsgfdg"); ts.add("adf"); for(Iterator it=ts.iterator();it.hasNext();){//TreeSet中的元素按字典序排序 System.out.println(it.next()); } } public static void test2() { Comparator comparator=new ComparatorByName(); TreeSet ts=new TreeSet(comparator); ts.add(new Person("zhangsan",21)); ts.add(new Person("lisi",24)); ts.add(new Person("lisi",25)); ts.add(new Person("wangwu",22)); ts.add(new Person("zhaoliu",25)); ts.add(new Person("zhaoai",25)); ts.add(new Person("zhouqi",27)); ts.add(new Person("zhaoai",25)); //com.zj.bean.Person cannot be cast to java.lang.Comparable for(Iterator it=ts.iterator();it.hasNext();){//TreeSet中的元素按字典序排序 System.out.println(it.next()); } } public static void test1() { TreeSet ts=new TreeSet(); ts.add("abc"); ts.add("hcd"); ts.add("abz"); ts.add("zfs"); ts.add("adf"); for(Iterator it=ts.iterator();it.hasNext();){//TreeSet中的元素按字典序排序 System.out.println(it.next()); } }}
package com.zj.set.demo;import java.util.Comparator;import com.zj.bean.Person;public class ComparatorByName implements Comparator { @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method stub if(!((o1 instanceof Person)&&(o2 instanceof Person))) throw new ClassCastException("类型错误"); Person p1=(Person)o1; Person p2=(Person)o2; int temp=p1.getAge()-p2.getAge(); return temp==0?p1.getName().compareTo(p2.getName()):temp;// return 1;//使TreeSet按元素存入顺序进行遍历// return -1;//使TreeSet按元素存入顺序逆序进行遍历// return 0;//使TreeSet只能接受一个元素 }}
六. Map接口(映射)
映射(map)是一个存储关键字和值的关联,或者说是“关键字/值”对的对象,即给定一个关键字,可以得到它的值。关键字和值都是对象,关键字必须是唯一的,但值是可以被复制的。
1.Map中常用的方法
Map一次添加一对元素,Collection一次添加一个元素。Map也称为双列集合,Collection称为单列集合。Map中存储的是键值对,Map集合中必须保证键的唯一性。Map中的常用方法:
(1)添加
value put(key,value);//返回以前与key关联的值,若没有针对key的映射关系,则返回null
(2)删除
void clear();//清空Map集合
value remove(key);//如果存在一个键的映射关系,则将其从映射中移除
(3)判断
boolean containsKey(key);//如果此映射包含指定键的映射方式,则返回true
boolean containsValue(value);//如果此映射将一个或多个键映射到指定值,则返回true
boolean isEmpty();//如果此映射未包含键值映射关系,则返回true
(4)获取
value get(key);//返回指定键所映射的值,若不包含该键的映射关系,则返回null
int size();//获取键值对的个数
(5)遍历
Set keySet();//返回此映射中所包含的键的Set视图
Set entrySet();//返回此映射中包含的映射关系的Set视图
Collection values();//返回此映射中包含的值的Collection视图
2.Map常用的具体实现类
(1)Hashtable:内部结构是哈希表,是同步的。不允许null作为键和值。
子类Properties:用来存储键值对型的配置文件信息,可以和I/O技术相结合。
(2)HashMap:内部结构是哈希表,是不同步的。允许null作为键和值。
(3)TreeMap:内部结构是二叉树,是不同步的。可以对Map集合中的键进行排序。
package com.zj.map.demo;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Set;public class MapDemo { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>();// test(map);// test2(map);// test3(map); test4(map); } public static void test4(Map<Integer, String> map) { map.put(1001, "zhaoliu"); map.put(1002, "wangwu"); map.put(1003, "lisi"); map.put(1004, "zhangsan"); map.put(1005, "lisi"); Collection<String> values=map.values();//values方法返回此映射中包含的值的Collection视图,Collection允许重复元素 for(Iterator<String> it=values.iterator();it.hasNext();){ System.out.println(it.next()); } } public static void test3(Map<Integer, String> map) { // TODO Auto-generated method stub map.put(1001, "zhaoliu"); map.put(1002, "wangwu"); map.put(1003, "lisi"); map.put(1004, "zhangsan"); //取出map中的所有元素。 //方式二: //原理:先通过entrySet方法获取映射中包含的映射关系所组成的set集合,再通过set的迭代器获取到每一个映射关系 Set<Map.Entry<Integer, String>> entrySet=map.entrySet();//获取映射中包含的映射关系的set集合 for(Iterator<Map.Entry<Integer, String>> it=entrySet.iterator();it.hasNext();){ Map.Entry<Integer, String> entry=(Map.Entry<Integer, String>)it.next(); //通过Map.Entry对象的getKey和getValue方法来获得键和值 System.out.println(entry.getKey()+":"+entry.getValue()); //System.out.println(entry.toString()); } } public static void test2(Map<Integer, String> map) { map.put(1001, "zhaoliu"); map.put(1002, "wangwu"); map.put(1003, "lisi"); map.put(1004, "zhangsan"); //取出map中的所有元素。 //方式一: //原理:先通过keySet方法获取map中所有的键所在的set集合,再通过set的迭代器获取到每一个键,对每一个键获取其对应的值即可 Set<Integer> keySet=map.keySet();//获取映射中所有键值组成的set集合 for(Iterator it=keySet.iterator();it.hasNext();){ Integer key=(Integer)it.next(); System.out.println(key+":"+map.get(key)); } System.out.println(map); } public static void test(Map<Integer,String> map){//学号和姓名 //1.添加元素 System.out.println(map.put(1001, "zhangsan")); map.put(1003, "zhaoliu"); System.out.println(map.put(1002, "lisi")); System.out.println(map.put(1002, "wangwu"));//存相同键,值会覆盖 map.put(1004, "zhouqi"); System.out.println(map); //2.删除 map.remove(1002); System.out.println(map); //3.判断 System.out.println(map.containsKey(1003)); //4.获取 System.out.println(map.get(1004)); }}
package com.zj.map.demo;import java.util.HashMap;import java.util.Iterator;import java.util.Set;import com.zj.bean.Student;public class HashMapDemo { public static void main(String[] args) { test(); } /** * 将学生对象和学生的归属地通过键与值存储到map集合中 */ public static void test() { HashMap<Student,String> hm=new HashMap<Student,String>(); hm.put(new Student("zhangsan",24), "北京"); hm.put(new Student("lisi",22), "上海"); hm.put(new Student("wangwu",23), "杭州"); hm.put(new Student("zhaoliu",26), "苏州"); hm.put(new Student("wangwu",23), "杭州"); Set<Student> keySet=hm.keySet(); for(Iterator<Student> it=keySet.iterator();it.hasNext();){ Student key=it.next(); System.out.println(key.getName()+":"+key.getAge()+"--"+hm.get(key)); } }}
package com.zj.map.demo;import java.util.Iterator;import java.util.Map;import java.util.Set;import java.util.TreeMap;import com.zj.bean.Student;import com.zj.set.demo.ComparatorByName;public class TreeMapDemo { public static void main(String[] args) { test(); } /** * 将学生对象和学生的归属地通过键与值存储到map集合中 */ public static void test() { TreeMap<Student,String> tm=new TreeMap<Student,String>(new ComparatorByName()); tm.put(new Student("zhangsan",24), "北京"); tm.put(new Student("lisi",22), "上海"); tm.put(new Student("wangwu",23), "杭州"); tm.put(new Student("zhaoliu",26), "苏州"); tm.put(new Student("wangwu",23), "杭州");// Set<Student> keySet=tm.keySet();// for(Iterator<Student> it=keySet.iterator();it.hasNext();){// Student key=it.next();// System.out.println(key.getName()+":"+key.getAge()+"--"+tm.get(key));// } Set<Map.Entry<Student,String>> entrySet=tm.entrySet(); for(Iterator<Map.Entry<Student,String>> it=entrySet.iterator();it.hasNext();){ Map.Entry<Student,String> entry=it.next(); System.out.println(entry.getKey().getName()+"::"+entry.getKey().getAge()+"---"+entry.getValue()); } }}
package com.zj.bean;public class Student extends Person { public Student(String name, int age) { super(name, age); }}
七. Utilities(静态工具类)
1. Collections
Collections工具类代码演示:
package com.zj.collections.demo;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;import com.zj.set.demo.ComparatorByLength;public class CollectionsDemo { public static void main(String[] args) { /* * Collections:是集合框架的工具类,里面的方法都是静态的 */// test1(); test2(); test3(); } public static void test3() { List<String> list=new ArrayList<String>(); List synList=Collections.synchronizedList(list);//返回指定列表支持的同步列表 } public static void test2() { List<String> list=new ArrayList<String>(); list.add("adsdf"); list.add("df"); list.add("hgadsdf"); list.add("ad"); list.add("ggfhadsdf"); list.add("zxc"); System.out.println(list); Collections.sort(list); System.out.println(list);// Collections.reverse(list);//反转指定列表中元素的顺序// System.out.println(list);// Comparator comp=Collections.reverseOrder();// 返回一个比较器,它强行逆转实现了 Comparable 接口的对象 collection 的自然顺序。// Collections.sort(list, comp);// System.out.println(list); Comparator comp2=Collections.reverseOrder(new ComparatorByLength()); Collections.sort(list, comp2); System.out.println(list); } public static void test1() { List<String> list=new ArrayList<String>(); list.add("adsdf"); list.add("df"); list.add("hgadsdf"); list.add("ad"); list.add("ggfhadsdf"); list.add("zxc"); System.out.println(list); String max=Collections.max(list);//获取最大的 System.out.println("max="+max); String maxLen=Collections.max(list, new ComparatorByLength());//获取最长的 System.out.println("maxLen="+maxLen); Collections.sort(list);//对list集合进行自然顺序的排序 System.out.println(list);// mySort(list);// System.out.println(list);//使用自己定义的mySort(List)方法进行排序 int index=Collections.binarySearch(list,"zxc"); System.out.println("index="+index);// Collections.sort(list, new ComparatorByLength());//根据指定比较器产生的顺序对指定列表进行排序// System.out.println(list); mySort(list, new ComparatorByLength());//使用自己定义的mySort(List,Comparator)方法,根据指定的比较器进行排序 System.out.println(list); } public static <T extends Comparable <? super T>>void mySort(List<T> list){ for(int i=0;i<list.size();i++){ for(int j=i+1;j<list.size();j++){ if(list.get(i).compareTo(list.get(j))>0){// T temp=list.get(i);// list.set(i, list.get(j));// list.set(j, temp); Collections.swap(list, i, j); } } } } public static <T extends Comparable <? super T>>void mySort(List<T> list,Comparator<? super T> c){ for(int i=0;i<list.size();i++){ for(int j=i+1;j<list.size();j++){ if(c.compare(list.get(i), list.get(j))>0){// T temp=list.get(i);// list.set(i, list.get(j));// list.set(j, temp); Collections.swap(list, i, j); } } } } }
2. Arrays
Arrays工具类代码演示:
package com.zj.arrays.demo;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class ArraysDemo { public static void main(String[] args) { /* * Arrays:集合框架工具类,里面的方法都是静态的 */// int[] arr={1,3,5,2,7,8,9,0};// System.out.println(myToString(arr));// // System.out.println(Arrays.toString(arr));// test1(); test2(); } /** * 重点:Collection接口中的toArray方法,将集合转成数组 * 好处:集合转成数组,可以对集合中元素的操作方法进行限定,不允许执行增删操作 */ public static void test2() { // TODO Auto-generated method stub List<String> list =new ArrayList<String>(); list.add("fsdf"); list.add("hgfhd"); list.add("asd"); //注意:toArray方法需要传入一个指定类型、指定长度的数组。 // 如果长度小于集合的size,那么该方法会创建一个和集合相同size的数组; // 如果长度大于集合的size,那么该方法会就会使用指定的数组存储集合中的元素,其他位置默认为null; // 所以建议,最后长度指定为集合的size String[] arr=list.toArray(new String[list.size()]); System.out.println(Arrays.toString(arr)); } /** * 重点:List asList(arr),将数组转成集合 * 好处:Arrays.asList通过可以使用集合的方法操作数组中的元素,与Collection.toArray一起充当数组与集合之间的桥梁 * 注意:数组的长度是固定的,所以对于集合的增删方法是不可以使用的,否则会发生java.lang.UnsupportedOperationException */ public static void test1() { String[] arr1={"ads","afdfdsf","nkk","fdjk"}; List list1=Arrays.asList(arr1); System.out.println(list1.contains("nkk"));// list.add("aaa");// 发生java.lang.UnsupportedOperationException,不支持的操作异常,不支持增删操作 System.out.println(list1); //注意:如果数组中的元素是对象,那么转成集合时,直接将数组中的元素作为集合中的元素进行集合存储 // 如果数组中的元素是基本数据类型数值,那么会将该数组作为集合中的元素进行存储,因为集合只能存储对象,不能存储基本数据类型 int[] arr2={2,4,6,7,1}; List<int[]> list2=Arrays.asList(arr2); System.out.println(list2);//list2中只有1个int[]数组对象 Integer[] arr3={2,4,6,7,1}; List<Integer> list3=Arrays.asList(arr3); System.out.println(list3);//list3中有5个Integer对象 } //源码:toString的经典实现 public static String myToString(int[] a) { if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) {//中间省略了条件判断,提高了效率(这种代码写法值得借鉴) b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } /*for (int i = 0; i<= iMax ; i++) {//中间判断,下面也要判断,效率低 b.append(a[i]); if (i == iMax) b.append("]"); else b.append(", "); } return b.toString();*/ }}
- [ java ] java基础集合!
- JAVA基础之集合
- java基础之集合
- java基础:集合connection
- java基础之 集合
- java基础10 集合
- java基础--集合
- java基础---集合类
- java基础知识点集合
- java基础 集合迭代器
- JAVA基础之集合
- Java集合框架基础
- java基础--HashSet集合
- java基础_09_集合
- 【Java基础】集合
- Java基础之 集合
- java基础__集合
- JAVA基础集合
- VC、VS2005调试技巧
- OpenGL编码剪裁算法Cohen-Surtherland算法
- Cause by:All WebView methods must be called on the same thread[问题已解决]
- 使用mp4v2产生mp4文件
- HDOJ 5546 Ancient Go (DFS)
- Java基础:集合
- NOIP2009Hankson的趣味题
- UITextField在弹出的键盘上方,加一个带有完成按钮的toolBar工具栏
- ionic infinite
- 银行卡BIN码大全
- 4路RS485继电器模块 电脑控制开关 PC智能控制器 工控板
- React Native 开发环境安装和配置
- Android组件——服务
- json字符串转换为对象,json字符串中含数组