1.MAP键值对
* Map是一个一个的键值对
* 键和值都可以是任意类型
* 键不可以重复,值可以重复
* 如果键重复,用新值覆盖旧值
* 键值对之间是无序的
//创建一个键值对容器
Map map= new HashMap<>();
//put放元素
map.put(1,"aa");
map.put(1,"bb");
map.put(2,"bb");
map.put(new Person("dd", 20), 123);
System.out.println(map);
//根据键来取值
Object o=map.get(1);
System.out.println(o);
Object o2=map.get(new Person());
System.out.println(o2);
System.out.println("========");
//Map的遍历
//1.取出所有的键的集合
Set set =map.keySet();
//遍历键
for (Object key : set) {
Object value=map.get(key);
System.out.println(key+"="+value);
}
System.out.println("========");
//2.取出所有的键值对,放入set中
Set<Map.Entry<Object, Object>> entrySet=map.entrySet();
for(Map.Entry<Object, Object> entry:entrySet){
Object key=entry.getKey();
Object value=entry.getValue();
System.out.println(key+"="+value);
}
//取出所有值
Collection values=map.values();
System.out.println(values);
2.Date
public void testDate ()throws Exception{
String srcDate="1997-07-17";
SimpleDateFormat format=new SimpleDateFormat("yyyy-mm-dd");
//把字符串类型的日期转为日期类型的日期
Date date=format.parse(srcDate);
System.out.println(date);
//把日期转为字符串
Date now=new Date();
SimpleDateFormat f=new SimpleDateFormat("yyyy年mm月dd日 hh时mm分ss秒");
String dst=f.format(now);
System.out.println(dst);
}
3.比较器:Comparable(内部比较器)和Compartor(外部比较器);
要实现比较器就要写接口(Comparable)和重写Comparable的方法;
compareTo(Object obj) ,该方法的返回值是 int 。如果返回值为正数,则表示当前对象(调用该方法的对象)比 obj 对象“大”;反之“小”;如果为零的话,则表示两对象相等
TreeSet排序的构造方法:
1、TreeSet():根据TreeSet中元素实现的 Comparable 接口的 compareTo 方法比较排序
2、TreeSet(Comparator comparator):根据给定的 comparator 比较器,对 TreeSet 中的元素比较排序
public int compareTo(Person o) {
int i=this.age-o.getAge();
if(i==0){
return this.getName().compareTo(o.getName());
}
return -i;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public voidtestPersonTreeSet(){
4.TreeSet、Comparable
/**
* 为什么要把Person转为Comparable?
* 自定义的类型以什么依据排序?
* 放入TreeSet中的元素必须排序,排序的方式有种
* 1.放入TreeSet中的元素所在的类实现Comparable接口,并重写Comparable
*
*/
Set<Person> presons=new TreeSet<>();
presons.add(new Person("aa",18));
presons.add(new Person("aa",14));
presons.add(new Person("baby",21));
System.out.println(presons);
}