可以利用多态的思维,将数组定义成父类,则数组中可以存放子类,当然最大的父类是Object!!!!
public class Test { public static void main(String[] args){ Object [] a = new Object[5]; a[0] = 1; a[1] = 1.1; a[2] = true; a[3] = "123"; a[4] = '1'; System.out.println(Arrays.toString(a));//[1, 1.1, true, 123, 1] } }数组内容的比较可以使用 equals()方法吗?
public class ArrayTest06 { public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(a.equals(b));//false } }数组是引用类型,使用equals()方法调用的是Object的equals()方法,执行的依然是==,也就是地址比较。
解决方案:
自己写工具类,先判断是否为空,再判断长度是否相同,最后顺序比较内容 public class ArrayEqualsTest07 { public static boolean isEquals(int[] a, int[] b) { if( a == null || b == null ) { return false; } if(a.length != b.length) { return false; } for(int i = 0; i < a.length; ++i ) { if(a[i] != b[i]) { return false; } } return true; } public static void main(String[] args) { int[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(isEquals(a,b)); System.out.println(Arrays.equals(a,b)); } } 利用Arrays.equals()方法比较1、数组长度不可变,那么数组怎么扩容呢?
原数组满了之后,可以新建一个新的容量更大的数组,将原数组中的数据拷贝到新数组中,原数组对象被 GC 回收,以后向新数组中存储数据。这就是数组的扩容。2、数组扩容涉及到数组的拷贝,数组拷贝会耗费大量的资源。
3、数组怎么优化,怎么样可以提高效率?
创建数组的时候,预先估计数组中存储的元素个数,给定初始化容量,减少数组的扩容次数,减少数组的拷贝,提高程序的执行效率不可以通过继承去重新定义方法,可以定义一个类,包含String类,然后再增强或者实现。
public class StringTest02 { public static void main(String[] args) { String s1 = "abc";//指向的常量池 String s2 = "abc";//指向的常量池 String s3 = new String("abc");//指向的是堆内存 System.out.println("s1==s2, " + (s1==s2));//true System.out.println("s2==s3, " + (s2==s3));//false System.out.println("s2 equlas s3," + (s2.equals(s3)));//true } } 当通过new关键字构建的时候,会在堆内存创建一个对象,在常量池创建一份对象,并且变量指向的是堆中对象的地址定义String时,尽量使用双引号定义,这样可以节约空间,重复利用
因为 String 是不可变对象,如果多个字符串进行拼接,将会形成多个对象,这样可能会造成内存溢出,会 给垃圾回收带来工作量,如下面的应用最好不要用 String
线程安全 != 保证拼接顺序
StringBuffer的线程安全只是保证了在一次append()中不会有其他线程进入
为了保证线程安全,包装类都是不可变类型。
基本类型包装类byteByteshortShortcharCharacterintIntegerlongLongfloatFloatdoubleDoublebooleanBoolean除了 Boolean 和 Character 外,其它的包装类都有 valueOf()和 parseXXX 方法 ,同时都是number的子类
自动装箱和拆箱是JDK1.5之后提供的,方便基本类型与包装类之间的转换
String、 int、 Integer 之间的转换
public class Test { public static void main(String[] args) { //String + Integer Integer a = new Integer("123"); String b = Integer.toString(123); //String + int int c = Integer.parseInt("123"); String d = String.valueOf(c); //int + Integer Integer e = 123; int f = e.intValue(); } }