Short类将一个原始类型为short的值包装在一个对象中。Short类型的对象包含一个类型为short的单一字段。
此外,该类还提供了几种方法,用于将short转换为String,将String转换为short,以及其他处理short时有用的常量和方法。
short b = 55;
String bb = "45";
// Construct two Short objects
Short x = new Short(b);
Short y = new Short(bb);
类图显示了Short类所提供的API/方法的列表。
在这篇文章中,我们将学习Shortwrapper类的几个重要方法。
**例子:**这个程序演示了Short封装类方法的用法。
package com.javaguides.corejava.wrapperclasses;
//*/*
/* This class to demonstrate Short wrapper class methods
/* @author javaguides.net
/*
/*/
public class ShortClassExample {
public static void main(String[] args) {
short b = 55;
String bb = "45";
// Construct two Short objects
Short x = new Short(b);
Short y = new Short(bb);
// toString()
System.out.println("toString(b) = " + Short.toString(b));
// valueOf()
// return Short object
Short z = Short.valueOf(b);
System.out.println("valueOf(b) = " + z);
z = Short.valueOf(bb);
System.out.println("ValueOf(bb) = " + z);
z = Short.valueOf(bb, 6);
System.out.println("ValueOf(bb,6) = " + z);
// parseShort()
// return primitive short value
short zz = Short.parseShort(bb);
System.out.println("parseShort(bb) = " + zz);
zz = Short.parseShort(bb, 6);
System.out.println("parseShort(bb,6) = " + zz);
//decode()
String decimal = "45";
String octal = "005";
String hex = "0x0f";
Short dec = Short.decode(decimal);
System.out.println("decode(45) = " + dec);
dec = Short.decode(octal);
System.out.println("decode(005) = " + dec);
dec = Short.decode(hex);
System.out.println("decode(0x0f) = " + dec);
System.out.println("bytevalue(x) = " + x.byteValue());
System.out.println("shortvalue(x) = " + x.shortValue());
System.out.println("intvalue(x) = " + x.intValue());
System.out.println("longvalue(x) = " + x.longValue());
System.out.println("doublevalue(x) = " + x.doubleValue());
System.out.println("floatvalue(x) = " + x.floatValue());
int hash = x.hashCode();
System.out.println("hashcode(x) = " + hash);
boolean eq = x.equals(y);
System.out.println("x.equals(y) = " + eq);
int e = Short.compare(x, y);
System.out.println("compare(x,y) = " + e);
int f = x.compareTo(y);
System.out.println("x.compareTo(y) = " + f);
short to_rev = 45;
System.out.println("Short.reverseBytes(to_rev) = " + Short.reverseBytes(to_rev));
}
}
输出。
toString(b) = 55
valueOf(b) = 55
ValueOf(bb) = 45
ValueOf(bb,6) = 29
parseShort(bb) = 45
parseShort(bb,6) = 29
decode(45) = 45
decode(005) = 5
decode(0x0f) = 15
bytevalue(x) = 55
shortvalue(x) = 55
intvalue(x) = 55
longvalue(x) = 55
doublevalue(x) = 55.0
floatvalue(x) = 55.0
hashcode(x) = 55
x.equals(y) = false
compare(x,y) = 10
x.compareTo(y) = 10
Short.reverseBytes(to_rev) = 11520
###参考资料
https://docs.oracle.com/javase/8/docs/api/java/lang/Short.html
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/08/short-wrapper-class-in-java.html
内容来源于网络,如有侵权,请联系作者删除!