包裝類:
int→Integer 例:
第一種: int a=10;
Integer a1=new Integer(a);
System.out.println("in");
第二種: int b=1314;
Integer b1=b;
System.out.println(b1);
把一個基本數據類型轉換為對應的包裝類型稱為自動裝箱。
Integer→int
Integer c=new Integer(1314);
int c1=c;
System.out.println(c1);
或者: Integer c=new Integer (1234);
int c1=c; //自動拆箱
int c2=c.intValue();
System.out.println(c2);
String→Integer
String str="1314";
Integer str1=new Integer(str);
System.out.println(str1);
或者: String str="5566";
int str1=Integer.parseInt(str);//把一個字符串通過parseInt方法快速轉換為int類型。
parseInt()方法與valueOf方法類似,parseInt返回的是int類型,而valueOf返回的是Integer類型。
Integer→String
Integer d=new Integer(12345);
String d1=d.toString();
System.out.println(d1);
Object類:
Object類中的toString()方法:
toString()方法返回該對象的字符串表示,用來顯示對象信息。
Object類中的equals()方法,if括號里常用的字符串比較,重寫了equals方法,括號里是對象時用法不同,
當一個子類重寫equals()方法與沒重寫equals方法時的比較(此例中name和code是Student類中屬性,有set,get方法):
沒重寫的例: Student stu=new Student();
stu.setCode("123");stu.setName("lilei");
Student stu1=new Student();
stu1.setCode("123");stu1.setName("lilei");
if(stu.equals(stu1)){
System.out.println(true);
}else{
System.out.println(false);
} //此例結果為false,雖然name和code的值相同;
在Student類中重寫equals()方法后上面的程序結果不同:
equals()方法的重寫為:
/*@Override
public boolean equals(Object obj) {
//1.判斷obj是否是Student類的對象
Student s = null;
if(obj instanceof Student) {
s = (Student)obj;
if(this.name.equals(s.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
再執行語句:
Student stu=new Student();
stu.setCode("123");stu.setName("lilei");
Student stu1=new Student();
stu1.setCode("123");stu1.setName("lilei");
if(stu.equals(stu1)){
System.out.println(true);
}else{
System.out.println(false);
}
結果為true,因為重寫的方法中有if(this.name.equals(s.getName())),name相同stu與stu1比較就相同了;
posted on 2011-10-31 11:37
魏文甫 閱讀(198)
評論(0) 編輯 收藏