黑马程序员技术交流社区
标题:
Map集合
[打印本页]
作者:
凝聚
时间:
2013-10-5 17:12
标题:
Map集合
本帖最后由 凝聚 于 2013-10-6 11:30 编辑
import java.util.*;
public class six {
public static void main(String[] args) {
HashMap<Student,String>h=new HashMap<Student,String>();
h.put(new Student("orchestra",22),"shanghai");///////////////////////////////////
Set<Student>key=h.keySet();
Iterator<Student>it=key.iterator();
while(it.hasNext())
{
Student stu=it.next();
String addr=h.get(stu);
System.out.println(stu+"..."+addr);
}
}
class Student implements Comparable <Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.age=age;
this.name=name;
}
public int compareTo (Student s)
{
int num=new Integer(this.age);
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public int hashCode()
{
return name.hashCode()+age*34;
}
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;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name+"..."+age;
}
}
}
这段代码中h.put(new Student("orchestra",22),"shanghai");这句语句有错误怎么回事再麻烦大家说一下 return name.hashCode()+age*34; 这句话中 age*34中*后的数字是什么意思
作者:
HM汪磊
时间:
2013-10-5 17:47
class Student不是静态的,加上public static class Student就可以啦,另外一个小细节,类名以大写字母开头。
作者:
张慧
时间:
2013-10-5 17:50
public static void main(String[] args)也是静态方法,只能访问静态成员,你在访问内部类的时候,需要实例化一个外部类,同个外部类再实例化内部类。如果你把内部类静态化了,在前面加个static ,是可以直接这么写的。
作者:
吴清源
时间:
2013-10-5 22:25
Student类是内部类,有三种处理方式:
一,你可以在类前面加static声明,这样在main中就可以直接调用
二,你可以h.put(new six().new Student("orchestra",22),"shanghai");先new一个six对象,然后通过这个对象在new一个内部类的实例
三,直接将Student类定义在six外部,不要作为内部类使用
作者:
凝聚
时间:
2013-10-6 09:40
再麻烦大家说一下 return name.hashCode()+age*34; 这句话中 age*34中*后的数字是什么意思
作者:
杨增坤
时间:
2013-10-6 11:14
凝聚 发表于 2013-10-6 09:40
再麻烦大家说一下 return name.hashCode()+age*34; 这句话中 age*34中*后的数字是什么意思 ...
return name.hashCode()+age*34;
这个是返回的哈希值,那个34不是固定的,写这个就是为了通过返回的哈希值来确定对象是否相同,后面加上乘以一个数字,这样是对象分的更精确,可以少判断equals方法,这样就减少判断次数,效率也提高了,
关于内部类的话,你这样想比较容易:把内部类看成成员来考虑,看放到了什么位置,如果放在了和类的成员同等位置,那么就把其看成成员,调用方式和类 调用成员是一样的,
要是把内部类放在了方法中,那么及就把其看成局部变量,那么调用方式也一样,
希望对你有帮助!继续加油!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2