本帖最后由 赵学刚 于 2012-12-5 00:42 编辑
问题:测试类并没有调用toString ,为什么会自动起到转换效果呢?谁能解析下测试类MapTest调用toString的过程。。。。。谢谢!!!- public class Student implements Comparable<Student> {
- private String name;
- private int age;
- private String address;
- public String toString(){
- return this.age+this.name;
- }
- Student (String name ,int age){
- this.age=age;
- this.name=name;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- //自定义哈希值指定集合元素存储到哈希表中
- public int hashCode(){
- return name.hashCode()+age*32;
-
- }
- //自定义比较方法
- public boolean equals(Object obj){
- if(!(obj instanceof Student))
- throw new ClassCastException("类型不匹配");
- Student s=(Student)obj;
- return this.name.equals(s.name)&&this.age==s.age;
- }
- @Override //当集合按二叉树存储时,可以按自然顺序排序
- public int compareTo(Student s) {
- int num=new Integer(this.age).compareTo(new Integer(s.age));
- if(num==0){
- return this.name.compareTo(s.name);
- }
- return num;
- }
- public class MapTest {
- /**
- * 需求:取出所有map元素
- */
- public static void main(String[] args) {
- Map<Student,String> map=new TreeMap<Student,String>();
- map.put(new Student("lisi1",123), "tianjingo");
- map.put(new Student("lisi2",12), "tianjingo");
- map.put(new Student("lisi3",121), "tianjingo");
- map.put(new Student("lisi2",127), "tianjingo");
- Set<Map.Entry<Student,String>> keySet=map.entrySet();
- Iterator<Map.Entry<Student,String>> it=keySet.iterator();
- while(it.hasNext()){
-
- Map.Entry<Student,String> me=it.next();
- Student key=me.getKey();
- String value=me.getValue();
- System.out.println(key+"==="+value);
-
- }
- }
- }
复制代码 |