黑马_blog4_集合框架

来源:互联网 发布:java socket断点下载 编辑:程序博客网 时间:2024/05/01 16:04

---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------

 

1集合框架(体系概述)

为什么会出现这么多的容器呢?

因为每一个容器对数据的存储方式都有不同,这个存储方式可以称之为:数据结构--数据在内存中的存储方式。

2集合框架(共性方法)

引入的包:import java.util.*;

创建一个集合容器,使用Collection接口的子类ArrayList

ArrayList aL=new ArrayList();

添加元素:aL.add(“java01”);

获取集合长度:aL.size();

打印集合:System.out.println(aL);

删除元素:aL.remove(“java02”);

  aL.clear();

判断元素:aL.contains(“java03”);//是否包含

          aL.isEmpty();//集合是否为空

取交集:aL1.retainAll(aL2);

取差集:aL1.removeAll(aL2);

注:add方法的参数类型是Object,以便于接收任意类型对象,集合中存储的都是对象的引用。

3集合框架(迭代器)

什么是迭代器?

其实就是集合的取出元素的方式。

把取出方式定义在了集合的内部,这样取出方式就可以直接访问每个集合内容的元素,那么取出方式就被定义成了内部类。而每一个容器的数据结构不同,所以取出的动作细节也不一样,但是都有共性内容:判断和取出,那么可以将这些共性抽取。那么这些内部类都符合一个规则Iterator,如何获取集合的取出对象呢?通过一个对外提供的方法iterator()

代码:

import java.util.*;class Test {public static void main(String[] args) {ArrayList<String> aL=new ArrayList<String>();aL.add("java01");aL.add("java02");aL.add("java03");Iterator it=aL.iterator();while(it.hasNext()){System.out.println(it.next());}}}

4集合框架(List结合共性方法)

Collection

   |---List:元素是有序的,元素可以重复,因为该集合体系有索引

   |---Set:元素是无序的,元素不可以重复,没有索引

List集合特有方法:凡是可以操作角标的方法都是该体系特有的方法。

增加元素:add(index,element)

          addAll(index,Collection)

删除元素:remove(index);

修改元素:setindext,element)

查找元素:get(index)

          subList(from,to)

          ListIterator();

获取所有元素

方式1for(int i=0;i<aL.size();i++)

{System.out.println(aL.get(i));}

方式2

Iterator it=aL.iterator();

while(it.hasNext())

{System.out.println(it.next());}

获取对象的位置:aL.indexOf(“java02”);

5集合框架(ListIterator)

代码:

//在迭代过程中,准备添加或者删除元素ArrayList aL=new ArrayList();aL.add("java02");aL.add("java03");Iterator it=aL.iterator();while(it.hasNext()){Object obj=it.next();if(obj.equals("java02"))it.remove();}System.out.println(obj);

List集合特有的迭代器,ListIteratorIterator的子接口,在迭代时,不可以通过集合对象的方法操作集合中的元素,因为会发生并发修改异常,所以,在迭代时,只能用迭代器的方法操作元素,可是Iterator方法是有限的,只能对元素进行判断,取出,删除的操作,如果想要其他的操作,如添加,修改等就需要使用其子接口,ListIterator,该接口只能通过List集合的ListIterator方法获取。

代码:

ArrayList aL=new ArrayList();aL.add("java02");aL.add("java03");ListIterator it=aL.listIterator();Object obj=null;while(it.hasNext()){obj=it.next();if(obj.equals("java02"))it.add("java009");}System.out.println(aL);

判断有没有前一个元素:it.hasPrevious();

判断有没有后一个元素:it.hasNext();

获取前一个元素:it.previous();

6集合框架(List集合具体对象的特点)

Collection

|--List:元素是有序的,元素可以重复。因为该集合体系有索引。

|--ArrayList:底层的数据结构使用的是数组结构。特点:查询速度很快。但是增删稍慢。线程不同步。

|--LinkedList:底层使用的链表数据结构。特点:增删速度很快,查询稍慢。线程不同步。

|--Vector:底层是数组数据结构。线程同步。被ArrayList替代了。因为效率低。

ArrayList 默认长度为10,超过10,再添加,就会new一个新的数组,50%延长,把原来的添加到新数组中来,再向后添加。

Vector 默认长度为10,超过10,100%延长。

一般使用ArrayListVector的效率低。

7集合框架(Vector中的枚举)

枚举就是Vector特有的取出方式。发现枚举和迭代器很像。其实枚举和迭代是一样的。

因为枚举的名称以及方法的名称都过长。所以被迭代器取代了。枚举郁郁而终了。

代码:

class VectorDemo {public static void main(String[] args) {Vector v = new Vector();v.add("java01");v.add("java02");v.add("java03");v.add("java04");Enumeration en = v.elements();while(en.hasMoreElements()){System.out.println(en.nextElement());}}}

8集合框架(LinkedList)

LinkedList:特有方法:

addFirst();

addLast();

 

getFirst();

getLast();

获取元素,但不删除元素。如果集合中没有元素,会出现NoSuchElementException

removeFirst();

removeLast();

获取元素,但是元素被删除。如果集合中没有元素,会出现NoSuchElementException

JDK1.6出现了替代方法。

offerFirst();

offerLast();

 

peekFirst();

peekLast();

获取元素,但不删除元素。如果集合中没有元素,会返回null不抛出异常

pollFirst();

pollLast();

获取元素,但是元素被删除。如果集合中没有元素,会返回null不抛出异常

9集合框架(LinkedList练习)

使用LinkedList模拟堆栈或者队列数据结构:

堆栈:先进后出,如同杯子

队列:先进先出,如同水管

代码:

import java.util.*;class DuiLie{private LinkedList link;DuiLie(){link = new LinkedList();}public void myAdd(Object obj){link.addFirst(obj);}public Object myGet(){return link.removeFirst();}public boolean isNull(){return link.isEmpty();}}

10集合框架(ArrayList练习1)

代码:

去除ArrayList集合中的重复元素。

注:迭代时,it.next()取一次,就用it.hasNext()判断一次。

import java.util.*;class  Test{public static void main(String[] args) {ArrayList aL=new ArrayList();aL.add("java01");aL.add("java01");System.out.println(singleElement(aL));}public static List singleElement(ArrayList aL){ArrayList temp=new ArrayList();Iterator it=aL.iterator();while(it.hasNext()){Object obj=it.next();if(!temp.contains(obj))temp.add(obj);}return temp;}}

11集合框架(ArrayList练习2)

将自定义对象作为元素存到ArrayList集合中,并去除重复元素。

比如:存人对象。同姓名同年龄,视为同一个人。为重复元素。

思路:

1,对人描述,将数据封装进人对象。

2,定义容器,将人存入。

3,取出。

注:List集合判断元素是否相同,依据是元素的equals方法。equals方法默认比较的是地址值,我们要让它按照我们的方式比较,需要重写equals方法。

代码:

import java.util.*;class  Test{public static void main(String[] args) {ArrayList aL=new ArrayList();aL.add(new Person("zhangsan",34));aL.add(new Person("lisi",34));aL.add(new Person("wangwu",33));aL.add(new Person("wangwu",33));aL.add(new Person("wangwu",33));aL.add(new Person("wangwu",33));aL=singleElement(aL);Iterator it=aL.iterator();while(it.hasNext()){Person p=(Person)it.next();System.out.println(p.getName()+"   "+p.getAge());}        System.out.println(aL.remove(new Person("wangwu",33)));}public static ArrayList singleElement(ArrayList aL){ArrayList temp=new ArrayList();Iterator it=aL.iterator();while(it.hasNext()){Object obj=it.next();if(!temp.contains(obj))temp.add(obj);}return temp;}}class Person{private String name;private int age;Person(String name,int age){this.name = name;this.age = age;}public boolean equals(Object obj){if(!(obj instanceof Person))return false;Person p = (Person)obj;return this.name.equals(p.name) && this.age == p.age;}public String getName(){return name;}public int getAge(){return age;}}

注意:调用contains(),contais()调用的是equals();

remove底层也调用了equals();

12集合框架(HashSet)

set:元素无序,不可重复。

HashSet:底层数据结构是哈希表

Set集合的功能和Collection功能一致。
代码:

import java.util.*;class Test {public static void main(String[] args) {HashSet hs=new HashSet();hs.add("java01");hs.add("java02");hs.add("java03");hs.add("java04");hs.add("java03");Iterator it=hs.iterator();while(it.hasNext()){System.out.println(it.next());}}}

13集合框架(HashSet存储自定义对象)

HashSet集合中存入自定义的对象,姓名和年龄相同为同一个人。

代码:

import java.util.*;class Test {public static void main(String[] args) {HashSet hs=new HashSet();hs.add(new Person("java01",22));hs.add(new Person("java02",22));hs.add(new Person("java02",22));Iterator it=hs.iterator();while(it.hasNext()){System.out.println(it.next());}}}class Person{private String name;private int age;public Person(String name,int age){this.name=name;this.age=age;}public String getName(){return this.name;}public int getAge(){return this.age;}public int hashCode(){return this.name.hashCode()+age*17;}public boolean equals(Object obj){if(!(obj instanceof Person)){return false;}Person p=(Person)obj;return this.name.equals(p.name)&&(this.age==p.age);}}

HashSet是如何保证元素唯一性的呢?

是通过元素的两个方法,hashCodeequals来完成。

如果元素的HashCode值相同,才会判断equals是否为true

如果元素的hashcode值不同,不会调用equals

13集合框架(HashSet判断和删除的依据)

hs.contains(new Person("java01",22));

hs.remove(new Person("java01",22))

注意:对于判断元素是否存在,以及删除等操作,依赖的方法是元素的hashcodeequals方法。

14集合框架(TreeSet)

Set:无序,不可以重复元素。

|--HashSet:数据结构是哈希表。线程是非同步的。

保证元素唯一性的原理:判断元素的hashCode值是否相同。

如果相同,还会继续判断元素的equals方法,是否为true

|--TreeSet:可以对Set集合中的元素进行排序。

底层数据结构是二叉树。

保证元素唯一性的依据:

compareTo方法return 0.

代码:

import java.util.*;class Test {public static void main(String[] args) {TreeSet ts=new TreeSet();ts.add("java01");ts.add("java06");ts.add("java02");ts.add("java08");ts.add("java00");Iterator it=ts.iterator();while(it.hasNext()){System.out.println(it.next());}}}
15集合框架(TreeSet存储自定义对象)

TreeSet集合中存储自定义对象,学生,想按照学生的年龄进行排序。

记住:排序时,当主要条件相同时,一定要判断一下次要条件。

代码:

import java.util.*;class Test {public static void main(String[] args) {TreeSet ts=new TreeSet();ts.add(new Student("zhangsan",23));ts.add(new Student("zhangsan",19));ts.add(new Student("zhangsan",33));ts.add(new Student("zhangsan",11));ts.add(new Student("zhangsan1",11));Iterator it=ts.iterator();while(it.hasNext()){Student s=(Student)it.next();System.out.println(s.getName()+"  "+s.getAge());}}}class Student implements Comparable{private String name;private int age;public Student(String name,int age){this.name=name;this.age=age;}public int compareTo(Object obj){if(!(obj instanceof Student))throw new RuntimeException("不是学生对象");Student s=(Student)obj;if(this.age>s.age)return 1;else if(this.age<s.age)return -1;else return this.name.compareTo(s.getName());}public String getName(){return this.name;}public int getAge(){return this.age;}}

实现Comparable接口,并复写CompareToObject obj)方法,Student类才具有比较性。

16集合框架(二叉树)

元素怎么存进去就怎么取出来

public int compareTo(Object obj)

{return 1;}

注:|--TreeSet:可以对Set集合中的元素进行排序。底层数据结构是二叉树。保证元素唯一性的依据:compareTo方法return 0.

TreeSet排序的第一种方式:让元素自身具备比较性。

元素需要实现Comparable接口,覆盖compareTo方法。

也种方式也成为元素的自然顺序,或者叫做默认顺序。

17集合框架(实现comparator方式排序)

TreeSet的第二种排序方式。

当元素自身不具备比较性时,或者具备的比较性不是所需要的。

这时就需要让集合自身具备比较性。

在集合初始化时,就有了比较方式。

代码:

import java.util.*;class  Test{public static void main(String[] args) {TreeSet ts=new TreeSet(new MyCompare());ts.add(new Student("java04",22));ts.add(new Student("java02",25));ts.add(new Student("java01",21));Iterator it=ts.iterator();while(it.hasNext()){Student s=(Student)it.next();System.out.println(s.getName()+" "+s.getAge());}}}class Student implements Comparable{private String name;private int age;public Student(String name,int age){this.name=name;this.age=age;}public String getName(){return this.name;}public int getAge(){return this.age;}public int compareTo(Object obj){Student s=(Student)obj;int num=new Integer(this.getAge()).compareTo(new Integer(s.getAge()));if(num==0){return this.getName().compareTo(s.getName());}return num;}}class MyCompare implements Comparator{public int compare(Object o1,Object o2){Student s1=(Student)o1;Student s2=(Student)o2;int num= s1.getName().compareTo(s2.getName());if(num==0){return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));}return num;}}

18集合框架(TreeSet练习)

按照字符串的长度排序:使用比较器

import java.util.*;class Test {public static void main(String[] args) {TreeSet ts=new TreeSet(new StringLengthComparator());ts.add("aaaa");ts.add("cbaa");ts.add("e9");Iterator it=ts.iterator();while(it.hasNext()){System.out.println(it.next());}}}class StringLengthComparator implements Comparator{public int compare(Object o1,Object o2){String s1=(String)o1;String s2=(String)o2;int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));if(num==0)return s1.compareTo(s2);return num;}}

19集合框架(泛型概述)

泛型:JDK1.5版本以后出现新特性。用于解决安全问题,是一个类型安全机制。

好处

1.将运行时期出现问题ClassCastException,转移到了编译时期。,

方便于程序员解决问题。让运行时问题减少,安全。,

2,避免了强制转换麻烦。

代码:

ArrayList<String> aL=new ArrayList<String>();aL.add("java01");aL.add("java02");Iterator<String> it=aL.iterator();while(it.hasNext()){String s=it.next();System.out.println(s);}

20集合框架(泛型使用)

泛型格式:通过<>来定义要操作的引用数据类型。

在使用java提供的对象时,什么时候写泛型呢?

通常在集合框架中很常见,

只要见到<>就要定义泛型。

其实<> 就是用来接收类型的。

当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

泛型比较器代码:

import java.util.*;class Test {public static void main(String[] args) {TreeSet<String> ts=new TreeSet<String>(new StringLengthComparator());ts.add("java02");ts.add("java01");ts.add("java001");Iterator<String> it=ts.iterator();while(it.hasNext()){String s=it.next();System.out.println(s);}}}class StringLengthComparator implements Comparator<String>{public int compare(String s1,String s2){int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));if(num==0)return s1.compareTo(s2);return num;}}

21集合框架(泛型类)

泛型类代码:

class Test {public static void main(String[] args) {Tool<Student> tL=new Tool<Student>();tL.setObject(new Student());Student s=tL.getObject();}}class Student{}class Worker{}class Tool<QQ>{private QQ q;public void setObject(QQ q){this.q=q;}public QQ getObject(){return this.q;}}

当类中要操作的引用数据类型不确定的时候,使用泛型类,早期使用的是Object来完成扩展,容易在运行时期强制类型转换出错。

22集合框架(泛型方法)

泛型类定义的泛型,在整个类中有效。如果被方法使用,

那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。

为了让不同方法可以操作不同类型,而且类型还不确定。

那么可以将泛型定义在方法上。

代码:

class Test {public static void main(String[] args) {Demo d=new Demo ();d.show(4);d.print("haha");}}class Demo{public<T> void show(T t){System.out.println("show"+t);}public<T> void print(T t){System.out.println("print"+t);}}

23集合框架(静态方法泛型)

静态方法不可以访问类上定义的泛型。

如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。

public static <W> method(W w)

24集合框架(泛型接口)

在实现接口的时候知道操作的是什么类型:

class Test {public static void main(String[] args) {InterImple in=new InterImple();in.show("hello");}}interface Inter<T>{public void show(T t);}class InterImple implements Inter<String>{public void show(String str){System.out.println(str);}}

在实现接口的时候不知道操作什么类型,在实例化的时候才知道。

class Test {public static void main(String[] args) {InterImple<Integer> in=new InterImple<Integer>();in.show(5);}}interface Inter<T>{public void show(T t);}class InterImple<T> implements Inter<T>{public void show(T t){System.out.println(t);}}

25集合框架(泛型限定)

通配符。也可以理解为占位符。

泛型的限定;

? extends E: 可以接收E类型或者E的子类型。上限。

? super E: 可以接收E类型或者E的父类型。下限

? extends E示例代码:

import java.util.*;class Test {public static void main(String[] args) {ArrayList<Person> aL=new ArrayList<Person>();aL.add(new Person("aaa1"));aL.add(new Person("aaa2"));aL.add(new Person("aaa3"));print(aL);ArrayList<Student> aL1=new ArrayList<Student>();aL1.add(new Student("aaa-01"));aL1.add(new Student("aaa_02"));aL1.add(new Student("aaa-03"));print(aL1);}public static void print(ArrayList<? extends Person> aL){Iterator<? extends Person> it=aL.iterator();while(it.hasNext()){System.out.println(it.next().getName());}}}class Person{private String name;public Person(String name){this.name=name;}public String getName(){return this.name;}}class Student extends Person{public Student(String name){super(name);}}? super E示例代码:import java.util.*;class Test {public static void main(String[] args) {TreeSet<Student> ts=new TreeSet<Student>(new Comp());ts.add(new Student("abc04"));ts.add(new Student("abc01"));ts.add(new Student("abc03"));Iterator<Student> sit=ts.iterator();while(sit.hasNext()){System.out.println(sit.next().getName());}TreeSet<Worker> tss=new TreeSet<Worker>(new Comp());tss.add(new Worker("wabc-03"));tss.add(new Worker("wabc-01"));tss.add(new Worker("wabc-04"));Iterator<Worker> wit=tss.iterator();while(wit.hasNext()){System.out.println(wit.next().getName());}}}class Comp implements Comparator<Person>{public int compare(Person p1,Person p2){return p1.getName().compareTo(p2.getName());}}class Person{private String name;public Person(String name){this.name=name;}public String getName(){return this.name;}}class Student extends Person{public Student(String name){super(name);}}class Worker extends Person{public Worker(String name){super(name);}}

26集合框架(Map概述)

Map集合:该集合存储键值对。一对一对往里存。而且要保证键的唯一性。

1,添加。

put(K key, V value) 

putAll(Map<? extends K,? extends V> m) 

2,删除。

clear() 

remove(Object key) 

3,判断。

containsValue(Object value) 

containsKey(Object key) 

isEmpty() 

4,获取。

get(Object key) 

size() 

values() 

entrySet() 

keySet() 

27集合框架(Map子类对象的特点)

Map

|--Hashtable:底层是哈希表数据结构,不可以存入nullnull值。该集合是线程同步的。jdk1.0.效率低。

|--HashMap:底层是哈希表数据结构,允许使用 null 值和 null 键,该集合是不同步的。将hashtable替代,jdk1.2.效率高。

|--TreeMap:底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。

Set很像。

其实大家,Set底层就是使用了Map集合。

注意:添加元素,添加元素,如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值

System.out.println("put:"+map.put("01","zhangsan1"));

System.out.println("put:"+map.put("01","wnagwu"));

28集合框架(Map_keySet)

map集合的两种取出方式:

Set<k> keySet:将map中所有的键存入到Set集合。因为set具备迭代器。所有可以迭代方式取出所有的键,在根据get方法。获取每一个键对应的值。

代码:

import java.util.*;class  Test{public static void main(String[] args) {Map<String,String> map=new HashMap<String,String>();map.put("01","zhangsan01");map.put("02","zhangsan02");map.put("03","zhangsan03");map.put("04","zhangsan04");Set<String> keys=map.keySet();Iterator<String> it=keys.iterator();while(it.hasNext()){String key=it.next();String value=map.get(key);System.out.println(key+"="+value);}}}

注意:Map集合的取出原理:将map集合转成set集合。在通过迭代器取出。

29集合框架(Map-entrySet)

Set<Map.Entry<k,v>> entrySet:将map集合中的映射关系存入到了set集合中,而这个关系的数据类型就是:Map.Entry

Entry其实就是Map中的一个static内部接口。

为什么要定义在内部呢?

因为只有有了Map集合,有了键值对,才会有键值的映射关系。关系属于Map集合中的一个内部事物。而且该事物在直接访问Map集合中的元素。

代码:

import java.util.*;class  Test{public static void main(String[] args) {Map<String,String> map=new HashMap<String,String>();map.put("01","zhangsan01");map.put("02","zhangsan02");map.put("03","zhangsan03");map.put("04","zhangsan04");Set<Map.Entry<String,String>> entry=map.entrySet();Iterator<Map.Entry<String,String>> it=entry.iterator();while(it.hasNext()){Map.Entry<String,String> me=it.next();String key=me.getKey();String value=me.getValue();System.out.println(key+"="+value);}}}

30集合框架(Map练习)

练习要求:

每一个学生都有对应的归属地。学生Student,地址String。学生属性:姓名,年龄。

注意:姓名和年龄相同的视为同一个学生。保证学生的唯一性。

1,描述学生。

2,定义map容器。将学生作为键,地址作为值。存入。

3,获取map集合中的元素。

import java.util.*;class  Test{public static void main(String[] args) {HashMap<Student,String> hm=new HashMap<Student,String>();hm.put(new Student("lisi1",22),"tianjing");hm.put(new Student("lisi1",22),"beijing");hm.put(new Student("lisi2",26),"shanghai");hm.put(new Student("lisi3",23),"nanjing");hm.put(new Student("lisi4",26),"wuhan");//第一种取出方式Set<Student> keys=hm.keySet();Iterator<Student> it=keys.iterator();while(it.hasNext()){Student stu=it.next();String address=hm.get(stu);System.out.println(stu+"  "+address);}//第二种取出方式Set<Map.Entry<Student,String>> entry=hm.entrySet();Iterator<Map.Entry<Student,String>> iter=entry.iterator();while(iter.hasNext()){Map.Entry<Student,String> me=iter.next();Student stu=me.getKey();String address=me.getValue();System.out.println(stu+"-------"+address);}}}class Student implements Comparable<Student>{private String name;private int age;public Student(String name,int age){this.name=name;this.age=age;}public int hashCode(){return this.name.hashCode()+this.age*37;}public boolean equals(Object obj){if(!(obj instanceof Student))throw new RuntimeException("类型不匹配");Student s=(Student)obj;return this.name.equals(s.name)&&this.age==s.getAge();}public int compareTo(Student s){int num=this.name.compareTo(s.getName());if(num==0){return new Integer(this.age).compareTo(new Integer(s.getAge()));}return num;}public String getName(){return this.name;}public int getAge(){return this.age;}public String toString(){return this.name+" "+this.age;}}

31集合框架(TreeMap练习)

利用treeMap存入学生对象:

import java.util.*;class  Test{public static void main(String[] args) {TreeMap<Student,String> hm=new TreeMap<Student,String>(new StuCom());hm.put(new Student("lisi1",22),"tianjing");hm.put(new Student("lisi1",22),"beijing");hm.put(new Student("lisi2",26),"shanghai");hm.put(new Student("lisi3",23),"nanjing");hm.put(new Student("lisi4",26),"wuhan");Set<Map.Entry<Student,String>> entry=hm.entrySet();Iterator<Map.Entry<Student,String>> iter=entry.iterator();while(iter.hasNext()){Map.Entry<Student,String> me=iter.next();Student stu=me.getKey();String address=me.getValue();System.out.println(stu+"-------"+address);}}}class StuCom implements Comparator<Student>{public int compare(Student s1,Student s2){int num=new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));if(num==0)return s1.getName().compareTo(s2.getName());return num;}}class Student implements Comparable<Student>{private String name;private int age;public Student(String name,int age){this.name=name;this.age=age;}public int hashCode(){return this.name.hashCode()+this.age*37;}public boolean equals(Object obj){if(!(obj instanceof Student))throw new RuntimeException("类型不匹配");Student s=(Student)obj;return this.name.equals(s.name)&&this.age==s.getAge();}public int compareTo(Student s){int num=this.name.compareTo(s.getName());if(num==0){return new Integer(this.age).compareTo(new Integer(s.getAge()));}return num;}public String getName(){return this.name;}public int getAge(){return this.age;}public String toString(){return this.name+" "+this.age;}}

32集合框架(TreeMap练习-字母出现的次数)

根据给定的字符串,统计各个字母出现的次数。

代码:

import java.util.*;class  Test{public static void main(String[] args) {System.out.println(charCount("rrrrdldlk"));}public static String charCount(String str){char[] chs=str.toCharArray();TreeMap<Character,Integer> tm=new TreeMap<Character,Integer>();for(int i=0;i<chs.length;i++){Integer value=tm.get(chs[i]);if(value==null){value=0;}tm.put(chs[i],value+1);}StringBuilder sb=new StringBuilder();Set<Map.Entry<Character,Integer>> entry=tm.entrySet();Iterator<Map.Entry<Character,Integer>> it=entry.iterator();while(it.hasNext()){Map.Entry<Character,Integer> me=it.next();Character c=me.getKey();Integer count=me.getValue();sb.append(c+"("+count+")");}return sb.toString();}}

33集合框架(Map扩展)

代码示例1

import java.util.*;class  Test{public static void main(String[] args) {HashMap<String,String> yure=new HashMap<String,String>();HashMap<String,String> jiuye=new HashMap<String,String>();HashMap<String,HashMap<String,String>> czbk=new HashMap<String,HashMap<String,String>>();yure.put("01","zhangsan1");yure.put("02","zhangsan2");jiuye.put("01","lisi1");jiuye.put("02","lisi2");czbk.put("jiuye",jiuye);czbk.put("yure",yure);Set<String> keys=czbk.keySet();Iterator<String> it=keys.iterator();while(it.hasNext()){String key1=it.next();HashMap<String,String> hs=czbk.get(key1);System.out.println(key1);Set<String> ks=hs.keySet();Iterator<String> iter=ks.iterator();while(iter.hasNext()){String key=iter.next();String value=hs.get(key);System.out.println(key+" "+value);}}}}

代码示例2

 import java.util.*;class  Test{public static void main(String[] args) {ArrayList<Student> list=new ArrayList<Student>();list.add(new Student("01",23));list.add(new Student("02",22));list.add(new Student("03",33));list.add(new Student("04",33));HashMap<String,ArrayList<Student>> czbk=new HashMap<String,ArrayList<Student>>();czbk.put("jiuye",list);czbk.put("yure",list);Set<String> keys=czbk.keySet();Iterator<String> it=keys.iterator();while(it.hasNext()){String key=it.next();System.out.println(key);ArrayList<Student> value=czbk.get(key);for(int i=0;i<list.size();i++){System.out.println(list.get(i).getName()+" "+list.get(i).getAge());}}}}class Student{private String name;private int age;public Student(String name,int age){this.name=name;this.age=age;}public String getName(){return this.name;}public int getAge(){return this.age;}}

34 集合(Collections工具类)

  排序:Collections.sort(list,new StrLenCom());

最大值:Collections.max(list,new StrLenCom());

这版查找:Collections.binarySearchlist,”aaa”,new StrLenCom());

将集合中的元素全都替换成它:Collections.fill(list,”pp”)

集合中元素替换:Collections.replaceAll(list,”oldValue”,”newValue”)

集合中元素反转:Collections.reverse(list)

强行逆转指定比较器顺序:Collections.reverseOrder(new StrLenCom());

强行逆转实现Comparable接口的对象collection的自然顺序:Collections.reverseOrder();

把元素随机排放:Collections.shuffle(list)

元素换位置:Collections.swap(list,1,2)

将非同步的变成同步的:Collections.synchronizedListlist

示例代码:

import java.util.*;class  Test{public static void main(String[] args) {ArrayList<String> list=new ArrayList<String>();list.add("sddd");list.add("dkjld");list.add("dkdk");Collections.sort(list,new StrLenCom());String max=Collections.max(list,new StrLenCom());System.out.println(list);System.out.println(max);}}class StrLenCom implements Comparator<String>{public int compare(String s1,String s2){int num= new Integer(s1.length()).compareTo(new Integer(s2.length()));if(num==0)return s1.compareTo(s2);return num;}}      

35 集合(Arrays工具类)

Arrays:用于操作数组的工具类。

将数组变成字符串:Arrays.toStringarr)

将数组变成List集合:Arrays.asList(arr);(不可以使用集合的增删方法)

*高级for循环

格式:

for(数据类型 变量名 被遍历的集合(Collection)或者数组)

{

}

对集合进行遍历。只能获取集合元素。但是不能对集合进行操作。

迭代器除了遍历,还可以进行remove集合中元素的动作。

如果是用ListIterator,还可以在遍历过程中对集合进行增删改查的动作。

传统for和高级for有什么区别呢?

高级for有一个局限性。必须有被遍历的目标。

建议在遍历数组的时候,还是希望是用传统for。因为传统for可以定义脚标。

*可变参数。

例如:

 public static void show(String str,int... arr)

{System.out.println(arr.length);}





---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------



 




 



 

 


 

0 0
原创粉丝点击