Java中的常见基础类(一)

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。Java中的常见基础类(一),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

八大包装类

Java里面针对八大基本数据类型都有对应的包装类型的实现,因为基本数据类型只有数据,而包装数据类型新增了很多功能(对数据的操作)

在包装类和基本数据类型之间可以自动进行类型转换~~~

//自动装箱		
Long l1 = 1l;
Integer i1 = 1;
Short s1 = 1;
Byte b1 = 1;
Boolean bo1 = true;
Character c1 = 'a';
Float f1 = 1f;
Double d1 = 1d;

//自动拆箱
Integer integer = new Integer(12);
int a = integer;
// ...

当然不只是能用自动装箱,也可以进行手动装箱和拆箱

Integer integer = new Integer(12);
//手动拆箱
int a1 = integer.intValue();
//手动装箱
Integer integer2 = Integer.valueOf(1);
//其他类型
Integer integer = new Integer(12);
int a1 = integer.intValue();
float v = integer.floatValue();
// ...
integer.longValue();
integer.doubleValue();
integer.shortValue();
integer.byteValue();

Integer类型的面试题

public static void main(String[] args) {
        Integer a = -129;
        Integer b = -129;
        System.out.println(a == b); //false
        Integer a2 = -128;
        Integer b2 = -128;
        System.out.println(a2 == b2); //true
    }

上面代码的结果一个是true,另一个是false,这是为什么?两个引用数据类型不应该是比较的是内存地址吗?

关于这个内存地址,应该两个都是false吧?

来,看源码!!!

public static Integer valueOf(int i) {
        //high = 127 ,  low = -128
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

从源码中可以看到,Integer包装类里面有一个缓存池,存放-128 ~ 127范围的数字,在这个范围里面的值,返回的都是同一个对象.

当然,其他类型的对象也可以尝试看源码…

String类的常见API

String 实质上是利用字符数组帮助存储字符
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

String 最终类,内容是不可修改的,一旦修改就会产生新的对象!!!

String s = "aaa";
String aaa = s.concat("aaa");
String substring = s.substring(0, 3);
String s1 = s.replaceFirst("a", "b");
System.out.println(s); // aaa

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/202494.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!