10-16学习笔记

来源:互联网 发布:淘宝提醒买家付款 编辑:程序博客网 时间:2024/05/01 17:07

今天一天下来个人觉得有2个很重要的重点,一是使用泛型的TreeSet集合的排序,二是遍历Map集合的两种方式。TreeSet使用泛型,也就是在定义的时候是TreeSet<Student> set=new TreeSet<Student>(),包括在使用迭代器的时候也需要指定类型了,Iterator<Student> it=set.iterator()TreeSet使用比较器的两种方式我也掌握了。然后今天的新知识点Map集合,它在存储的时候是存储两个(Key,Value,然后它添加元素使用的方法是put方法,keyvalue是映射关系,我们可以通过get(key)方法取得key对应的value,如果不存在,则返回null;如果我们不知道key的时候可以通过keySet方法先取得keySet集合,然后遍历key集合得到每个元素的key,再通过key获得对应的value。遍历Map集合的第二种方式就比较复杂了,第一步是得到Map集合中的key-value映射关系,类型是Map.Entry,第二步是遍历Map.Entry集合,得到key-value映射,第三步是通过Map.Entry中的getKeygetValue方法得到keyvalue

总体来说,今天讲的东西基本掌握了,然后明天早上起来将下午第三节课的两道练习题再联系一遍。

1.泛型的TreeSet两种使用比较器方式

/*
TreeSet
1.自然顺序
2.比较器
*/
import java.util.*;
class CompareDemo
{
public static void main(String[] args)
{
  TreeSet<Student> set=new TreeSet<Student>(new MyComparator());//定义一个泛型TreeSet集合
  set.add(new Student("asq",22));//新建三个Student对象然后存入set集合中
  set.add(new Student("ljd",21));
  set.add(new Student("abc",28));
  //Iterator<Student> it=set.iterator();
  for (Iterator<Student> it=set.iterator();it.hasNext() ; )//迭代器,遍历集合
  {
   Student s=it.next();
   System.out.println(s);

}
}
}
//定义一个类实现Comparator接口
class MyComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2){
  return s1.name.compareTo(s2.name);
}
}
/*
//实现Compareable接口,重写compareTo方法
class Student implements Comparable<Student>
{
String name;

int age;
public Student(String name,int age){//带name和age的有参构造函数
  this.name=name;
  this.age=age;
}
public int compareTo(Student s1){//重写Compareable接口的compareTo方法
  return this.age-s1.age;//比较年龄返回值
}
public String toString(){//重写toString方法
  return "姓名:"+name+"  age:"+age;
}
}
*/

2.遍历Map集合的2种方式代码示例

/*
Map集合想要遍历元素,不能使用Iterator
它有两种方式得到
1.setKey,然后通过get得到
2.使用Map的entrySet方法。
*/
import java.util.*;

 

class MapDemo
{
public static void main(String[] args)
{
  Map<Integer,Person> map=new HashMap<Integer,Person>();//泛型HashMap集合
  map.put(1234,new Person(60,"asq"));//存入四个元素
  map.put(456,new Person(50,"ljd"));
  map.put(234,new Person(80,"ruanw"));
  map.put(987,new Person(70,"abc"));
  //遍历Map集合的第一种方式
  /*
  Set<Integer> keys=map.keySet();//通过map集合中的keySet方法得到key的Set集合
  for (Iterator<Integer> it=keys.iterator();it.hasNext() ; )//遍历set集合
  {
   int key=it.next();
   Person s=map.get(key);//通过map集合中的get方法得到key映射的value
   System.out.println(s);
  }

*/
  //第二种方式
  //得到Map集合中的key-value映射关系
  Set<Map.Entry<Integer,Person>> set=map.entrySet();
  for (Iterator<Map.Entry<Integer,Person>> itset=set.iterator();itset.hasNext() ; )
  {
   Map.Entry<Integer,Person> kv=itset.next();
   //使用Map.Entry接口提供的方法getKey getValue得到元素
   int in=kv.getKey();
   Person p=kv.getValue();
   System.out.println(in+""+p);
}

}
}

class Person
{
String name;
int age;
public Person(int age,String name){

 

this.name=name;
  this.age=age;
}
public String toString(){//重写toString方法
  return "姓名:"+name+"\t年龄:"+age;
}

}