posts - 27,comments - 2,trackbacks - 0
包装类:
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 魏文甫 阅读(191) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: