import java.util.*;
class Noname1
{
public static void main(String[]args)
{
TreeMap<Student,String>tm=new TreeMap<Student,String>();
tm.put(new Student("lisi1",23),"beij");
tm.put(new Student("lisi2",22),"nanij");
tm.put(new Student("lisi3",25),"hj");
tm.put(new Student("lisi4",26),"sij");
Set<Map.Entry<Student,String>>entrySet=tm.entrySet();
Iterator<Map.Entry<Student,String>>it=entrySet.iterator();
while(it.hasNext())
{
Map.Entry<Student,String>me=it.next();
Student stu=me.getKey();
String addr=me.getValue();
System.out.println(stu+"::::"+addr);
}
}
}
class Student implements Comparable<Student>
{
public String name;
public int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
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 int hashCode()
{
return name.hashCode()+age*23;
}
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;
}*/
}
学习黑马毕向东老师基础视频中案例,在Map练习中需要用到定义的Student类。在注释掉最后三个方法的情况下,编译通过,运行结果如下:
---------- 运行Java程序 ----------
Student@62363f9::::nanij
Student@623640f::::beij
Student@623643f::::hj
Student@6236457::::sij
输出完成 (耗时 0 秒) - 正常终止
将最后的toString注释去掉后,运行正常了。
不是很理解底层原因,先收着做个记录。另外贴一下toString的用法如下:
ToString()有4个重载方法,可以转换成7种格式:
C
货币
2.5.ToString("C")
¥2.50
D
十进制数
25.ToString("D5")
00025
E
科学型
25000.ToString("E")
2.500000E+005
F
固定点
25.ToString("F2")
25.00
G
常规
2.5.ToString("G")
2.5
N
数字
2500000.ToString("N")
2,500,000.00
X
十六进制
255.ToString("X")
FF
formatCode 是可选的格式化代码字符串。(详细内容请搜索“格式化字符串”查看)
必须用“{”和“}”将格式与其他字符分开。如果恰好在格式中也要使用大括号,可以用连续的两个大括号表示一个大括号,即: “{{”或者“}}”。
常用格式举例:
(1) int i=12345;
this.textBox1.Text=i.ToString();
//结果 12345(this指当前对象,或叫当前类的实例)
this.textBox2.Text=i.ToString("d8");
//结果 00012345
(2) int i=123;
double j=123.45;
string s1=string.Format("the value is {0,7:d}",i);
string s2=string.Format("the value is {0,7:f3}",j);
this.textBox1.Text=s1 ;
//结果 the value is 123
this.textBox2.Text=s2;
//结果 the value is 123.450
(3)double i=12345.6789;
this.textBox1.Text=i.ToString("f2"); //结果 12345.68
this.textBox2.Text=i.ToString("f6");
//结果 12345.678900
(4)double i=12345.6789;
this.textBox1.Text=i.ToString("n"); //结果 12,345.68
this.textBox2.Text=i.ToString(“n4”); //结果 12,345.6789
(5)double i=0.126;
string s=string.Format("the value is {0:p}",i);
this.textBox1.Text=i.ToString("p"); //结果 12.6%
this.textBox2.Text=s; //结果 the value is 12.6%
(6) DateTime dt =new DateTime(2003,5,25);
this.textBox1.Text=dt.ToString("yy.M.d");
//结果 03.5.25
this.textBox2.Text=dt.ToString(“yyyy年M月”);
//结果 2003年5月
(7) int i=123;
double j=123.45;
string s=string.Format("i:{0,-7},j:{1,7}",i,j);
//-7表示左对齐,占7位
this.textBox1.Text=s ;
//结果i:123 ,j: 123.45