部分知识点整理 (二)

2014-11-24 11:24:38 · 作者: · 浏览: 13
ent实现比较性

class Student implements Comparable

{

//定义Student私有属性

private String name;

private int age;

//构造Student函数,初始化

Student(String name,int age)

{

this.name = name;

this.age = age;

}

//公共访问方法,访问私有属性

public String getName()

{

return name;

}

public int getAge()

{

return age;

}

//复写Comparator中的compare方法,自定义比较器

public int compareTo(Object obj)

{

//判断是否属于Student类型,否则抛异常

if (!(obj instanceof Student))

throw new RuntimeException("NotSuchTypeException");

//按年龄大小比较,相同则比较姓名大小,不同返回两年龄之差

Student s = (Student)obj;

if (this.age > s.age)

return this.age-s.age;

else if (this.age == s.age)

{

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

}

return this.age-s.age;

}

}

//定义比较器,实现Comparator接口

class MyCompare implements Comparator

{

//重写Comparator中的compare方法,按姓名顺序排序

public int compare(Object o1,Object o2)

{

//判断给定对象是否为Student类,否则抛异常

if (!((o1 instanceof Student) && (o2 instanceof Student)))

throw new RuntimeException("NotSuchTypeException");

//将给定对象强转为Student类

Student s1 = (Student)o1;

Student s2 = (Student)o2;

//比较名字,返回数值,相同则比较年龄

int n = s1.getName().compareTo(s2.getName());

if (n == 0)

return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));

return n;

}

}

//测试

class TreeSetComDemo

{

public static void main(String[] args)

{

//TreeSet ts = new TreeSet();

//创建集合,加入接口类参数,并添加元素

TreeSet ts = new TreeSet(new MyCompare());

ts.add(new Student("li01",25));

ts.add(new Student("li02",20));

ts.add(new Student("li01",22));

ts.add(new Student("li05",24));

ts.add(new Student("li08",40));

//打印集合中元素

printE(ts);

}

//定义打印集合中元素的功能

public static void printE(TreeSet ts)

{

//迭代器方法获取

Iterator it = ts.iterator();

while (it.hasNext())

{

//将返回的元素(Object类)强转为Student类

Student s = (Student)it.next();

System.out.println(s.getName() + "---" + s.getAge());

}

}

}

集合中的两种取出方式?

keySet()和entrySet()方法

1、keySet()方法获取元素

原理:将Map集合中的所有键存入到Set集合中,因为Set集合具备迭代器,所以可以用迭代方式取出所有的键,再根据get方法获取每一个键对应的值。简单说就是:Map集合---->Set集合 ---->迭代器取出

import java.util.*;

class KeySetDemo

{

public static void main(String[] args)

{

//创建Map集合,并添加元素

Map map = new HashMap();

map.put(2,"zhangsan");

map.put(6,"lisi");

map.put(3,"wangwu");

map.put(4,"heihei");

map.put(5,"xixi");

//获取map集合中的所有键的Set集合

Set keySet = map.keySet();

//有了Set集合就可以获取其迭代器,取值

Iterator it = keySet.iterator();

while (it.hasNext())

{

Integer i = it.next();

String s = map.get(i);

System.out.println(i + " = " + s);

}

}

}

2、entrySet()方法获取元素:

原理:将Map集合中的映射关系存入到了Set集合中,而这个映射关系的数据类型是Map.Entry,在通过迭代器将映射关系存入到