当前位置: 首页 > 编程日记 > 正文

Java基础教程——包装类

Java出道之时,自诩为“纯面向对象的语言”,意思是之前的所谓“面向对象语言”不纯。
但是,有人指责Java也不纯——8种基本类型并非类类型。为此,Java为他们提供可对应的类类型,是为“包装类”。

包装类

Java的八种基本数据类型用起来很方便,但不支持面向对象的编程机制,不属于Object继承体系,没有成员方法可调用。某些场合下,只能使用对象类型,不能使用基本类型,因此基本类型需要对应的包装类。

比如集合的定义:List<Integer> list;
写为List<int> list;就错了

Java提供了基本类型对应的包装类(Wrapper Class):

包装类一般就是把基本类型的首字母小写变为大写,但是int和char除外,它们的包装类要用全称。
下表中将int和char的写法加粗。

基本类型包装类
byteByte
intInteger
shortShort
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

另有一种说法,说Java中有9种基本类型,还要加一个void,其包装类是Void,但这种说法没有被普遍接受。

装箱和拆箱的概念

基本类型→(转为)→包装类,是为装箱
包装类→(转为)→基本类型,是为拆箱

1648799-20190713012817914-1212595181.png

1648799-20190713012830127-685591122.png

JDK 1.5开始就提供了自动装箱、自动拆箱功能。借助该功能,开发者可以把基本类型当做对象使用,也可以把包装类的实例当做基本类型变量使用。

public class Test包装类 {public static void main(String[] args) {int a1 = 1000;// 定义基本类型Integer objA = a1; // 自动装箱:Integer←intint a2 = objA; // 自动拆箱:int←IntegerSystem.out.println(a2);}
}

上述代码的解析:
| | int a1 = 1000; | | |
| -------- | -------------------------- | ----------- | -------------------------------- |
| 自动装箱 | Integer objA =a1; | Integer←int | 本质上调用了Integer.valueOf(...) |
| 自动拆箱 | int a2 = objA; | int←Integer | 本质上调用了objA.intValue() |

包装类可以通过new实例化来构造
除Character类外,其它的包装类都有parseXxx方法:字符串→基本数据类型
包装类有valueOf方法:字符串→包装类对象

示例代码(比较枯燥,瞅一眼就行):

public class Test构造包装类 {public static void main(String[] args) {构造包装类();parseXxx_str_to_基本类型();valueOf_str_to_Wrapper();}static void 构造包装类() {System.out.println("---new 包装类---");Boolean objBool = new Boolean(true);Character objChar = new Character('X');Byte objByte = new Byte((byte) 10);Short objS = new Short((short) 50);Integer objInt = new Integer(100);Long objLong = new Long(1000);Float objF = new Float(3.14);Double objD = new Double(3.1415);System.out.println(objBool);System.out.println(objChar);System.out.println(objByte);System.out.println(objS);System.out.println(objInt);System.out.println(objLong);System.out.println(objF);System.out.println(objD);}static void parseXxx_str_to_基本类型() {String str = "123";System.out.println("---除Character类外,包装类都有parseXxx方法");System.out.println("---parseXxx:字符串→基本数据类型值");byte b = Byte.parseByte(str);short s = Short.parseShort(str);int i = Integer.parseInt(str);long l = Long.parseLong(str);float f = Float.parseFloat(str);double d = Double.parseDouble(str);boolean bl = Boolean.parseBoolean("TruE");System.out.println(i);System.out.println(s);System.out.println(b);System.out.println(l);System.out.println(f);System.out.println(d);System.out.println(bl);}static void valueOf_str_to_Wrapper() {String str = "123";System.out.println("---valueOf方法:字符串→包装类对象");Byte objByte = Byte.valueOf(str);Short objShort = Short.valueOf(str);Integer objInt = Integer.valueOf(str);Long objLong = Long.valueOf(str);Float objF = Float.valueOf(str);Double objD = Double.valueOf(str);Boolean objB = Boolean.valueOf("true");Character obkChar = Character.valueOf('C');System.out.println(objByte);System.out.println(objShort);System.out.println(objInt);System.out.println(objLong);System.out.println(objF);System.out.println(objD);System.out.println(obkChar);System.out.println(objB);}
}

Java中100等于100,1000不等于1000

public class Java1000 {public static void main(String[] args) {Integer a1 = 100;Integer a2 = 100;System.out.println(a1 + "==" + a2 + ":" + (a1 == a2));a1 = 1000;a2 = 1000;System.out.println(a1 + "==" + a2 + ":" + (a1 == a2));}
}

100==100:true
1000==1000:false


原因:JDK源码的Integer类中,将-128~127做了缓存处理。
看看这段缓存:

package java.lang;
……
public final class Integer extends Number implements Comparable<Integer> {
……private static class IntegerCache {static final int low = -128;static final int high;static final Integer cache[];static {// high value may be configured by propertyint h = 127;……high = h;……// range [-128, 127] must be interned (JLS7 5.1.7)assert IntegerCache.high >= 127;}private IntegerCache() {}}……
}

改改这段缓存:(看懂大概即可)

import java.lang.reflect.Field;
import java.util.Arrays;
public class TestInteger {public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {// 说明:IntegerCache是Integer中的一个内部类// 源码:private static class IntegerCache{...}// 1.取出Integer中定义的内部类(包括公共、私有、保护)Class<?>[] classes = Integer.class.getDeclaredClasses();System.out.println("Class数组:" + Arrays.toString(classes));Class<?> classCache = classes[0];System.out.println("IntegerCache:" + classCache);// 2.取成员变量:cache// 源码:static final Integer cache[];Field fieldCache = classCache.getDeclaredField("cache");System.out.println("Integer cache[]:" + fieldCache);fieldCache.setAccessible(true);// 3.取出cache的值// field.get(obj):返回指定对象上由此Field表示的字段的值Integer[] newCache = (Integer[]) fieldCache.get(classCache);System.out.println("Integer[]:" + Arrays.toString(newCache));// 0 : -128// 1 : -127// 2 : -126// ...// 127 : -1// 128 : 0// 129 : 1// 130 : 2// 131 : 3// 132 : 4// 133 : 5newCache[132] = newCache[133];int a = 2;int b = a + a;// public PrintStream printf(String format, Object ... args)// 用的是Object类型,取包装类System.out.println("println:" + a + "+" + a + "=" + b); // 2+2=4System.out.printf("printf:%d + %d = %d\n", a, a, b); // 2+2=5newCache[132] = 1999;System.out.println("println:b = " + b);// println:正常的4System.out.printf("printf:b = %d", b);// printf:新值1999}
}

为什么System.out.printf的结果都是我们修改的值呢?可以推测,printf一定是到缓存中去取值了。

看看printf的源码:

public PrintStream printf(String format, Object ... args)

第二个参数是Object类型的(还是个可变参数),包装类是Object的子类,这里正是用的多态,用Object代表包装类的对象,取的正是Integer中的值,在-128~127范围内,取的正是缓存里的值。

最大值和最小值

通过包装类,我们可以取出数值类型的最大值和最小值,这些值在范围判断的时候很重要,但是非天才是记不住的,包装类可以帮我们快速找出来。

public class MAX_MIN {public static void main(String[] args) {System.out.println(Integer.MAX_VALUE);System.out.println(Integer.MIN_VALUE);System.out.println(Long.MAX_VALUE);System.out.println(Long.MIN_VALUE);System.out.println(Double.MAX_VALUE);System.out.println(Double.MIN_VALUE);}
}

2147483647
-2147483648
9223372036854775807
-9223372036854775808
1.7976931348623157E308
4.9E-324

*Java7增加的包装类功能:compare比较值的大小

public class TestIntegercompare {public static void main(String[] args) {Integer a1 = 100;Integer a2 = 100;System.out.println(a1 + "==" + a2 + ":" + (a1 == a2));// FALSEa1 = 1000;a2 = 1000;System.out.println(a1 + "==" + a2 + ":" + (a1 == a2));// FALSE// 包装类.compare方法:比较值的大小(大于:1/等于:0/小于:-1)System.out.println(a1 + "==" + a2 + ":" + Integer.compare(a1, a2));System.out.println("1 VS 2 : " + Integer.compare(1, 2));System.out.println("2 VS 1 : " + Integer.compare(2, 1));System.out.println("1 VS 1 : " + Integer.compare(1, 1));}
}

*Java8增强的包装类,主要是支持无符号运算。

无符号数的最高位不再被当做符号位(不支持负数,最小值为0)

public class Java8Wapper {public static void main(String[] args) {byte b = -1;int unsignedInt = Byte.toUnsignedInt(b);System.out.println(unsignedInt);long unsignedLong = Byte.toUnsignedLong(b);System.out.println(unsignedLong);}
}

255
255

转载于:https://www.cnblogs.com/tigerlion/p/11179167.html

相关文章:

linux kernel list_head

​​​​​​​Play with kernel list_head, three exampleshttps://www.fatalerrors.org/a/play-with-kernel-list_head-three-examples-of-super-cattle.html一篇介绍linux 内核链表的非常精彩的文章。

oracle rman实时备份吗,ORACLE-RMAN自动备份和恢复

以下介绍的是每周1-6增量备份&#xff0c;每周日全量备份。通过系统启动自动化任务[oracleorcl ~]$ crontab -l10 00 * * 0 /home/scripts/rmanlevel0.sh10 00 * * 1,2,3,4,5,6 /home/scripts/rmanlevel1.sh30 00 * * * /home/oracle/report/awr.sh[oracleorcl ~]$ cat /home…

hdu 5438 Ponds 拓扑排序

Ponds Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/contests/contest_showproblem.php?pid1001&cid621Description Betty owns a lot of ponds, some of them are connected with other ponds by pipes, and there will not be more than o…

CentOS6安装nodejs

Nodejs是JavaScript的一种运行环境&#xff0c;是一个服务端的JavaScript解释器。 NPM是Nodejs的包管理器。 Nodejs包含npm&#xff0c;所以安装完nodejs后npm默认也被安装。 安装步骤&#xff1a; # /usr/local/srcwget http://nodejs.org/dist/v6.7.0/node-v6.7.0-linux-…

Codeforces Round #FF 446 C. DZY Loves Fibonacci Numbers

參考&#xff1a;http://www.cnblogs.com/chanme/p/3843859.html 然后我看到在别人的AC的方法里还有这么一种神方法&#xff0c;他预先设定了一个阈值K,当当前的更新操作数j<K的时候&#xff0c;它就用一个类似于树状数组段更的方法&#xff0c;用一个 d数组去存内容&#x…

Java 基本概念

Java 基本概念 1. Java 语言的优点? 简单、高效 Java 语言与 C 类似&#xff0c;如果用户了解 C 和面向对象的概念&#xff0c;就可以很快编写出 Java 程序&#xff1b;此外&#xff0c;Java 又不同于诸如 C 语言提供的各种各样的方法&#xff0c;它只提供了基本的方法&#x…

list_for_each_safe

list_for_each_safeBidirect-list list_for_each_safe().https://biscuitos.github.io/blog/LIST_list_for_each_safe/

oracle恢复是怎么看进度,Oracle中查看慢查询进度的脚本分享

Oracle一个大事务的sql往往不知道运行到了哪里,可以使用如下sql查看执行进度。代码如下:404_6set linesize 400;H_404_6set pagesize 400;H_404_6col sql_text format a100;H_404_6col opname format a15;H_404_6SELECT se.sid,H_404_6opname,H_404_6TRUNC (sofar / totalwork …

第三周 9.13-9.19

9.13 长春OL。 9.14-9.15 什么都没干。 9.16-9.17 补题。 9.18 什么都没干。 9.19 沈阳OL。 本周就是什么都没干。转载于:https://www.cnblogs.com/Aguin/p/4805509.html

vue-devTools插件安装流程

vue-devTools插件安装流程 本文主要介绍 vue的调试工具 vue-devtools 的安装和使用 工欲善其事, 必先利其器, 快快一起来用vue-devtools来调试开发你的vue项目吧 安装: 1.到github下载&#xff1a;&#xff08;下载一定要记得是master环境的代码&#xff0c;默认克隆后进入…

基于ipfire的open***功能--client to net (Roadwarrior)配置(一)

Client-to-Net configuration (Roadwarrior)全局配置第一步应该是生成服务证书来激活ipfire上的open***。完成这个后&#xff0c;全局配置就可以使用了。为了激活open***所需的接口&#xff0c;open***服务监听的地方&#xff0c;你需要勾选界面里的方框。如何勾选&#xff0c;…

oracle update from多表性能优化一例

这几天测试java内存数据库&#xff0c;和oracle比较时发下一个update from语句很慢&#xff0c;如下&#xff1a; update business_newset fare1_balance_ratio (select BALANCE_RATIO from bfare2where bfare2.exchange_type business_new.exchange_type andbfa…

Sorry, Sarah

Sorry, Sarah

C#中Winform程序中如何实现多维表头【不通过第三方报表程序】

问题&#xff1a;C#中Winform程序中如何实现多维表头。 在网上搜了很多方法&#xff0c;大多数方法对于我这种新手&#xff0c;看的都不是很懂。最后在新浪博客看到了一篇比较易懂的文章&#xff1a;【DataGridView二维表头与合并单元格】 大体的思路如下&#xff1a; 1.新建一…

斗地主发牌编程PHP,JAVA代码之斗地主发牌详解

package com.oracle.demo01;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Map;public class Doudizhu {public static void main(String[] args) {//1.创建扑克牌MapMap pookernew HashMap();//创建所有key所在的容器A…

2022-2028年中国自动化设备市场研究及前瞻分析报告

【报告类型】产业研究 【报告价格】4500起 【出版时间】即时更新&#xff08;交付时间约3个工作日&#xff09; 【发布机构】智研瞻产业研究院 【报告格式】PDF版 本报告介绍了中国自动化设备行业市场行业相关概述、中国自动化设备行业市场行业运行环境、分析了中国自动化…

转发:某些函数需要将其一个或多个实参连同类型不变地转发给其他函数

16.47 编写你自己版本的翻转函数&#xff0c;通过调用接受左值和右值引用参数的函数来测试它。 #include<iostream> #include<string> #include<utility> using namespace std;template <typename T> int compare(const T &a ,const T &b) {if…

pycharm远程调试或运行代码

第一步&#xff1a;开始 第二步&#xff1a;设置远程服务器 第三步&#xff0c;查看 第四步&#xff0c;选择解释器&#xff0c;和指定文件映射路径&#xff08;相对上一步指定的相对路径&#xff09; 转载于:https://www.cnblogs.com/jeshy/p/11182359.html

LTE随机接入过程

随机接入的基本流程 Msg3和Msg4只有基于竞争的随机接入才存在&#xff0c;之所以叫Msg3/Msg4是因为不同的随机接入情况&#xff0c;Msg3/Msg4的消息不相同(本文稍后介绍)。 下图中的参数<ra-ResponseWindowSize>和<mac-ContentionResolutionTimer>来自SIB2中的rach…

workday与oracle,workingday与workday的区别 – 手机爱问

2005-04-11for的用法&#xff26;&#xff2f;&#xff32;到底应该怎么用&#xff1f;对于for的用法的确很多&#xff0c;可用作介词和连词&#xff0c;介词用法尤为丰富。以下详细列出了用法和句例&#xff0c;供你参考。for 1 preposition1used to say who is intended to g…

OGRE 2.1 Windows 编译

版权所有&#xff0c;转载请注明链接 OGRE 2.1 Windows 编译 环境&#xff1a;  Windows 7 64Bit  Visual Studio 2012  OGRE 2.1  CMake 2.8.12.1 OGRE&#xff1a;  OGRE官方推出了最新的OGRE2.1版本&#xff0c;链接地址&#xff1a;    https://bitbucket.or…

IDEA集成Docker插件实现一键自动打包部署微服务项目

一. 前言 大家在自己玩微服务项目的时候&#xff0c;动辄十几个服务&#xff0c;每次修改逐一部署繁琐不说也会浪费越来越多时间&#xff0c;所以本篇整理通过一次性配置实现一键部署微服务&#xff0c;实现真正所谓的一劳永逸。 二. 配置服务器 1. Docker安装 服务器需要安…

PHP的学习--PHP的引用

引用是什么 在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针&#xff0c;替代的是&#xff0c;引用是符号表别名。注意在 PHP 中&#xff0c;变量名和变量内容是不一样的&#xff0c;因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文…

谈一谈浏览器解析CSS选择器的过程【前端每日一题-6】

谈一谈浏览器解析CSS选择器的过程&#xff1f; 这是一道发散题&#xff0c;可以根据自己的理解自行解答。 在开始前&#xff0c;我们必须了解一个真相&#xff1a;为什么排版引擎解析 CSS 选择器时一定要从右往左解析&#xff1f; 简单的来说&#xff1a;浏览器从右到左进行查找…

LTE: MIB和SIB,小区选择和重选规则

LTE 中MIB/SIB内容可以参考&#xff1a;https://blog.csdn.net/wowricky/article/details/51348613 MIB/SIB的详细内容参考下面两张图 MIB,SIB1,SIB2 可以关注下小区选择的参数&#xff0c;用特殊颜色表示 36.304 - 5.2.3.2 Cell Selection Criterion S准则&#xff0c;需要…

linux 生成dll文件,Linux和Windows平台 动态库.so和.dll文件的生成

Linux动态库的生成1、 纯cpp文件打包动态库将所有cpp文件和所需要的头文件放在同一文件夹&#xff0c;然后执行下面命令gcc -shared - fpic *.c -o xxx.so&#xff1b;g -stdc17 - fpic *.cpp -o xxx.so&#xff1b;[C17标准&#xff0c;需要高版本gcc&#xff0c;本人采用gcc …

Form表单提交前进行JS验证的3种方式

1. 提交按钮的onclick事件中验证 <script type"text/javascript"> function check(form) { return true; }</script> <form> <input type"submit" name"submit1" value"登陆" οnc…

2022-2028年中国椎间孔镜行业市场研究及前瞻分析报告

【报告类型】产业研究 【报告价格】4500起 【出版时间】即时更新&#xff08;交付时间约3个工作日&#xff09; 【发布机构】智研瞻产业研究院 【报告格式】PDF版 本报告介绍了中国椎间孔镜行业市场行业相关概述、中国椎间孔镜行业市场行业运行环境、分析了中国椎间孔镜行…

mysql 错误:1166 解决办法

原因&#xff1a;检查字段里面是不是有空格&#xff0c;去掉就可以了转载于:https://www.cnblogs.com/zhizhan/p/3950453.html

优先级队列(小顶堆)的dijkstra算法

php实现迪杰斯特拉算法&#xff0c;并由小顶堆优化 1 <?php2 3 class DEdge4 {5 public $nextIndex, $length;6 7 public function __construct($nextIndex, $length)8 {9 $this->nextIndex $nextIndex;10 $this->length $length;11 …