美文网首页
包装类、String等常用类

包装类、String等常用类

作者: Finlay_Li | 来源:发表于2019-04-07 16:40 被阅读0次

    包装类(包裹类 Wrapper) :

    1. 定义
      Java 针对八种 基本数据类型 提供了相应的包装类

    2. 目的
      使得可以创建对象

    3. 对应列表
      | 基本数据类型 | 包装类 |
      | ------ | ------ | ------ |
      | byte本 | Byte |
      | int | Integer |
      | long | Long |
      | float | Float |
      | double | Double |
      | char | Character |
      | boolean | Boolean |

    4. 基本数据类型与包装类之间的转换

    • 装箱:将基本数据类型转换成对应的包装类
      ①使用对应包装类的构造器
      ②使用对应包装类的静态方法 valueOf()

    • 拆箱:将包装类转换成对应的基本数据类型
      ①通过对应包装类的 xxxValue()
      xxx :代表基本数据类型

    1. 基本数据类型、包装类 与 String 之间的转换
    • 基本数据类型、包装类 转换成 String
      ①String str = i + "";
      ②使用对应包装类的静态方法 toString()
      ③使用 String 类的静态方法 valueOf()

    • String 转换成 基本数据类型、包装类
      ①通过对应包装类的构造器
      ②使用对应包装类的静态方法 parseXxx()
      ③使用对应包装类的静态方法 valueOf()

    1. 自动装箱与自动拆箱(jdk1.5 后)
      Integer num = 10; //自动装箱
      int i = num; //自动拆箱
      Integer num1 = 100;
      Integer num2 = 100;
      System.out.println(num1 == num); //true
      Integer num3 = 129;
      Integer num4 = 129;
      System.out.println(num3 == num4);//false

    注意:Integer 提供了一个小的缓存(-128 ~ 127) 之间,若需要装箱的值在该取值范围内,则从缓存中取一个实例
    若超出该取值范围内,则 new Integer() 实例

    1. 示例
    public class WrapperTest {
        
        //String 转换成对应的基本数据类型、包装类
        @Test
        public void test6(){
            
            String str1 = "123";
            int num = Integer.parseInt(str1);
            System.out.println(num);
            
            String str2 = "15.6";
            double d1 = Double.parseDouble(str2);
            System.out.println(d1);
            
            String str3 = "false";
            boolean b1 = Boolean.parseBoolean(str3); //除了 true 以外,其他都为 false
            System.out.println(b1);
            
            System.out.println("----------------------------------------------------");
            
            Integer num1 = new Integer(str1);
            System.out.println(num1);
            
            Double d2 = new Double(d1);
            System.out.println(d2);
            
            System.out.println("----------------------------------------------------");
            
            Integer num2 = Integer.valueOf(str1);
            System.out.println(num2);
            
            Double d3 = Double.valueOf(str2);
            System.out.println(d3);
        }
        
        //基本数据类型、包装类 转换成 String
        @Test
        public void test5(){
            int a = 10;
            
            String str1 = a + "";
            
            String str2 = Integer.toString(a);
            System.out.println(str2);
            
            float f1 = 15.6f;
            String str3 = Float.toString(f1);
            System.out.println(str3);
            
            char ch = 'a';
            String str4 = Character.toString(ch);
            System.out.println(str4);
            
            System.out.println("------------------------------");
            
            String str5 = String.valueOf(a);
            System.out.println(str5);
            
            String str6 = String.valueOf(f1);
            System.out.println(str6);
            
            String str7 = String.valueOf(ch);
            System.out.println(str7);
        }
        
        //自动装箱与自动拆箱
        @Test
        public void test4(){
            /*int a = 10;
            
            Integer num = a;
            
            int b = num;*/
            
            Integer num1 = 100;
            Integer num2 = 100;
            System.out.println(num1 == num2); //true
            
            Integer num3 = 150;
            Integer num4 = 150;
            System.out.println(num3 == num4);//false
        }
        
        //拆箱
        @Test
        public void test3(){
            //装箱
            Integer num = new Integer(10);
            
            //拆箱
            int a = num.intValue();
            System.out.println(a);
            
            Float f1 = new Float(15.6f);
            float f2 = f1.floatValue();
            System.out.println(f2);
            
            Boolean b1 = new Boolean(true);
            boolean b2 = b1.booleanValue();
            System.out.println(b2);
        }
        
        //装箱
        @Test
        public void test2(){
            int a = 10;
            
            Integer num = Integer.valueOf(a);
            System.out.println(num);
            
            float f1 = 15.6f;
            Float f2 = Float.valueOf(f1);
            System.out.println(f2);
        }
        
        //装箱
        @Test
        public void test1(){
            int a = 10;
            
            Integer num = new Integer(a);
            System.out.println(num);
            
            System.out.println(Integer.MAX_VALUE);
            System.out.println(Integer.MIN_VALUE);
            
            System.out.println(Integer.toBinaryString(a));
            System.out.println(Integer.toHexString(a));
            System.out.println(Integer.toOctalString(a));
            
            System.out.println("-----------------------");
            
            float f1 = 15.6f;
            Float f2 = new Float(f1);
            System.out.println(f2);
            System.out.println("-----------------------");
            
            char ch = 'a';
            Character ch2 = new Character(ch);
            System.out.println(ch2);
        }
    }
    

    java.lang.String

    1. 为什么String是不可变的字符序列?
      String str1 = "abc";
      String str2 = new String("abc");
      使用“ ”括起来的都是不可变常量。因为它在内存中 是 固定长度的 char[]

    2. str1和str2二者的区别?

    • str1:代表一个对象,至少在内存中开辟一块内存空间。
      (str1)常量池
    • str2:代表两个对象,至少在内存中开辟两块内存空间。
      (str2 ) 堆内存
      ( "abc")方法区中的常量池
    1. 内存图


      image.png
    • 经典例题
    //下列程序运行的结果
    public class Test1 {
        String str = new String("good");
        char[] ch = { 't', 'e', 's', 't' };
        public void change(String str, char ch[]) {
            str = "test ok";      good   test ok
            ch[0] = 'g';          gest
        }
        public static void main(String[] args) {
            Test1 ex = new Test1();
            ex.change(ex.str, ex.ch);
            System.out.print(ex.str + " and ");  good    gets
            System.out.println(ex.ch);
        }
    }
    A.good and test
    B.good and gest
    C.test ok and test
    D.test ok and gest
    
    1. 思路:
      1 main程序执行开始
      2 执行创建对象
      3 调用方法
      4 输出结果

    2. 内存图


      image.png

    StringBuffer 和 StringBuilder

    1. 定义
      可变的字符序列。
      二者拥有兼容的 API (说明两者用法一模一样)

    2. 区别
      StringBuffer :是线程安全的,因此效率低
      StringBuilder :是线程不安全的,因此效率高

    3. 常用方法:

    • StringBuffer append(String str) : 添加
    • StringBuffer insert(int offset, String str) : 插入
    • StringBuffer replace(int start, int end, String str):替换
    • int indexOf(String str) :返回子串的位置索引
      int lastIndexOf()
    • String substring(int start, int end):截取子字符串序列
    • StringBuffer delete(int start, int end):删除一段字符串
    1. 三者的创建
    • String创建
      String str="abc";
      String str1=new String("abc");
    • StringBuffer 创建
      String Buffer sb=new StringBuffer("abce");
    • StringBuilder创建
      String Buffer sb=new StringBuffer("bdef");
    1. 三者的互相转换
    • String—>StiringBuffer
      方法一:Buffer/Builder构造器

      方法二:StiringBuffer append()(拼串)

    • StringBuffer—>String
      方法一: String toString()
      方法二:String 构造器

    • StringBuilder—>String(二者拥有兼容的 API)

    1. 三者效率对比
      StringBuilder > StringBuffer > String

    java.util.Date

    1. 表示当前的时间,精确到毫秒

    2. java.text.DateFormat
      一个抽象类,用于格式化日期/时间。

    3. java.text.SimpleDateFormat
      是 DateFormat 的子类

    4. 运用

    //获取当前系统时间    
    public void test1() throws ParseException {
            Date date = new Date();
            System.out.println(Date);
    }
        
    //格式化时间
    public void test2() throws ParseException {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
            String strDate = sdf.format(date);
            System.out.println(strDate);
            //转换回系统时间
            Date newDate = sdf.parse(strDate);
            System.out.println(newDate);
    }
    

    java.lang.Math 类

    用于数学运算

    1. double ceil(double d) : 返回不小于d的最小整数
    2. double floor(double d): 返回不大于d的最大整数
    3. int round(float f) : 返回最接近f的int型(四舍五入)
    4. long round(double d):返回最接近d的long型
    5. double max(double d1, double d2) : 返回较大值
    6. int min(int i1, int i2) : 返回较小值
    7. double random() : 返回一个大于等于0.0并且小于1.0的随机数

    java.util.Calendar

    日历类

        @Transactional(rollbackFor = Exception.class)
        public void start() {
            synchronized (AdvPoolJobHandler.class) {
                //当前时间
                Timestamp timestamp = new Timestamp(new Date().getTime());
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String checkTime = simpleDateFormat.format(timestamp);
    
                String cycleContent = "7";
                String value = generateDate(cycleContent);
        }
    
        private String generateDate(String cycleContent) {
            //地区
            Calendar calendar = Calendar.getInstance(Locale.CHINA);
            //模式,加天数
            calendar.add(Calendar.DAY_OF_MONTH, +Integer.parseInt(cycleContent));
            //格式化
            Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(timestamp);
            //响应结果
            return format;
        }
    

    java.math.BigDecimal

    支持任意精度的double数

    1. 加减乘除
     public BigDecimal add(BigDecimal value);                        //加法
     public BigDecimal subtract(BigDecimal value);                   //减法 
     public BigDecimal multiply(BigDecimal value);                   //乘法
     public BigDecimal divide(BigDecimal value);                     //除法
    
    1. 四舍五入
        @Test
        public void test2() {
            double num = 111231.5585;
            BigDecimal b = new BigDecimal(num);
            //保留2位小数
            double result = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            System.out.println(result);  //111231.56
        }
    

    BigDecimal.setScale()方法用于格式化小数点

    setScale(1)表示保留一位小数,默认用四舍五入方式
    setScale(1,BigDecimal.ROUND_DOWN)直接删除多余的小数位,如2.35会变成2.3
    setScale(1,BigDecimal.ROUND_UP)进位处理,2.35变成2.4
    setScale(1,BigDecimal.ROUND_HALF_UP)四舍五入,2.35变成2.4
    setScaler(1,BigDecimal.ROUND_HALF_DOWN)四舍五入,2.35变成2.3,如果是5则向下舍

    1. BigDecimal比较
      BigDecimal是通过使用compareTo(BigDecimal)来比较的
        @Test
        public void test4() {
            BigDecimal a = new BigDecimal("1");
            BigDecimal b = new BigDecimal("2");
            BigDecimal c = new BigDecimal("1");
            int result1 = a.compareTo(b);
            int result2 = a.compareTo(c);
            int result3 = b.compareTo(a);
     
            System.out.println(result1);  //-1
            System.out.println(result2);  //0
            System.out.println(result3);  //1
        }
    

    相关文章

      网友评论

          本文标题:包装类、String等常用类

          本文链接:https://www.haomeiwen.com/subject/jppsiqtx.html