在一个java文件中写多个类。不过只能有一个public所修饰的类,所以将A和B类前的public修饰符去掉即可,最终代码如下:
1、Integer是int提供的封装类,而int是Java的基本数据类型;
2、Integer默认值是null,而int默认值是0;
3、声明为Integer的变量需要实例化,而声明为int的变量不需要实例化;
4、Integer是对象,用一个引用指向这个对象,而int是基本类型,直接存储数值。
public class TestInteger {
public static void main(String[] args) {
int i1=123;
Integer i2=123;
Integer i3=new Integer(123);
System.out.println(i1==i2);
System.out.println(i1==i3);
System.out.println(i3==i2);
}
}
分别输出 true true false
①无论如何,Integer与new Integer不会相等。不会经历拆箱过程,i3的引用指向堆,而i2指向专门存放他的内存(常量池),他们的内存地址不一样,所以为false
②java在编译Integer i2 = 123的时候,被翻译成-> Integer i2 = Integer.valueOf(123);而valueOf()函数会对-128到127之间的数进行缓存
③int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比
泛型
无论泛型的类型形参传入哪一种是哪一种类型实参,对于JAVA来说,它们依然被当做同一个类来处理,在内存中也占用同一块内存空间。因此在静态方法、静态初始化块或者静态变量的声明和初始化中不允许使用形参。
class R<T>{
static T info;//非法
public static void bar(T msg);//非法
}
static <T> void fromArrayToCollection(T[] a,Collection<T> c) {
for (T o : a) {
c.add(o);
}
}
Integer类是Number类的子类
泛型通配符的上下限
<? extends T>//上限
Integer和int的区别
1、Integer是int提供的封装类,而int是Java的基本数据类型;
2、Integer默认值是null,而int默认值是0;
3、声明为Integer的变量需要实例化,而声明为int的变量不需要实例化;
4、Integer是对象,用一个引用指向这个对象,而int是基本类型,直接存储数值。
public class TestInteger {
public static void main(String[] args) {
int i1=123;
Integer i2=123;
Integer i3=new Integer(123);
System.out.println(i1==i2);
System.out.println(i1==i3);
System.out.println(i3==i2);
}
}
分别输出 true true false
①无论如何,Integer与new Integer不会相等。不会经历拆箱过程,i3的引用指向堆,而i2指向专门存放他的内存(常量池),他们的内存地址不一样,所以为false
②java在编译Integer i2 = 123的时候,被翻译成-> Integer i2 = Integer.valueOf(123);而valueOf()函数会对-128到127之间的数进行缓存
③int和integer(无论new否)比,都为true,因为会把Integer自动拆箱为int再去比
int 与Integer的自动装箱与拆箱。
String对象和基本类型变量之间的转换:
String对象转化为基本类型变量:
int it1=Integer.parseInt(str);
int it2=new Integer(str);
基本类型变量转化为String对象:
String ftStr=String.valueOf(2.345f);
String intStr="123";
int iti1=Integer.parseInt(intStr);
System.out.println(iti1);
String strs1=String.valueOf(2.345f);
System.out.println(strs1);
泛型
无论泛型的类型形参传入哪一种是哪一种类型实参,对于JAVA来说,它们依然被当做同一个类来处理,在内存中也占用同一块内存空间。因此在静态方法、静态初始化块或者静态变量的声明和初始化中不允许使用形参。
class R<T>{
static T info;//非法
public static void bar(T msg);//非法
}
但是泛型方法可以实现
静态方法不可以 访问 类上定义的泛型,但是可以将泛型定义在方法上 public <T> void print(Q q)
泛型方法的方法签名比普通方法的签名多了类型形参声明,类型形参声明以尖括号栝起来,多个类型形参之间以逗号分隔。泛型方法的申明,前面要加尖括号<T>static <T> void fromArrayToCollection(T[] a,Collection<T> c) {
for (T o : a) {
c.add(o);
}
}
Integer类是Number类的子类
泛型通配符的上下限
<? extends T>//上限
<? super T>//下限