学习笔记之面向对象编程17(容器之Comparable接口,Map接口)

来源:互联网 发布:中国移动视频软件 编辑:程序博客网 时间:2024/05/22 04:36

(一)Comparable接口

所以实现“排序”的类都实现了java.lang.comparable接口,Comparable接口中只有一个方法:public  int  comparaTo(object  obj);该方法:返回0表示this==obj;返回正数表示this>obj;返回负数表示this<obj;实现了comparable接口的类通过实现comparaTo方法从而确定该类对象的排列顺序。

(二)Map接口

实现Map接口的类用来存储“键-值”对;

Map接口的实现类有HashMap和TreeMap等;

Map类中存储的“键-值”对通过键来标识,所以键值不能重复;

import java.util.*;public class Test06 {public static void main(String[] args){Map m1 = new HashMap();Map m2 = new HashMap();m1.put("one", new Integer(1));m1.put("two", new Integer(2));m1.put("three", new Integer(3));m2.put("A", new Integer(1));m2.put("B", new Integer(2));System.out.println(m1.size());System.out.println(m1.containsValue(new Integer(1)));if(m1.containsKey("one")){int i = ((Integer)m1.get("two")).intValue();System.out.println(i);}Map m3 = new HashMap(m1);m3.putAll(m2);System.out.println(m3);}}


运行结果:

3
true
2
{A=1, B=2, two=2, three=3, one=1}