码迷,mamicode.com
首页 > 其他好文 > 详细

常用类

时间:2015-03-12 11:34:45      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

6.3.1 Object类

它是所有类,数组,枚举类的父类
Java允许把所有类型的对象赋给Object类型的变量
它有如下几个方法

  • boolean equals(Object obj):
  • protected void finalize():当系统没有引用变量引用到该对象时,垃圾回收器调用此方法来清理该对象的资源
  • Class< ? > getClass():
  • int hashCode():
  • String toString():
  • protected clone():帮助其他对象来实现自我克隆,就是得到一个当前对象的副本,而且二者之间完全隔离。
    • 步骤:
    • 1.自定义类实现Cloneable接口(标记性接口),接口里没有方法。
    • 2.自定义类实现自己的clone()方法
    • 3.实现clone()方法时通过super.clone();调用Object实现的clone()方法来得到该对象的副本,并返回该副本
      实例:CloneTest.java
package code;
class Address{
    private String detail;
    public Address(String detail){
        this.detail = detail;
    }
}
class User implements Cloneable{
    private int age;
    Address address;
    public User(int age){
        this.age = age;
        address = new Address("广州市天河区");
    }
    protected User clone()throws CloneNotSupportedException{
        return (User)super.clone();
    }
}
public class CloneTest{
    public static void main(String [] args)throws CloneNotSupportedException{
        User u1 = new User(11);
        User u2 = u1.clone();
        System.out.println(u1 == u2);
        System.out.println(u1.address == u2.address);
    }
}

false
true

Object类提供的clone()方法不仅能简单地处理”复制“的问题,而且很高效,
但是它虽然简单易用,但只是”浅克隆“—它只克隆该对象所有成员变量值,不会对引用类型的成员变量值所引用的对象进行克隆,
技术分享

6.3.2 Objects类

如果不确定一个引用变量是否为null,贸然调用toString()方法,则可能引发NullPointerException异常,但如果使用Objects类提供的toString(Object o)方法,就不会引发空指针异常。它会返回“null”字符串。

Java为工具类的命名习惯是添加一个字母s,比如操作数组工具类是Arrays,操作集合的工具类是Collections

package code;
import java.util.*;
public class ObjectsTest{
    static ObjectsTest obj;
    public static void main(String []args){
        System.out.println(Objects.toString(obj));
        System.out.println(Objects.hashCode(obj));
        System.out.println(Objects.requireNonNull(obj,"obj参数不能是null!"));
    }
}

null
0
Exception in thread “main” java.lang.NullPointerException: obj参数不能是null!
at java.util.Objects.requireNonNull(Objects.java:228)
at code.ObjectsTest.main(ObjectsTest.java:8)

上面的requireNonNull()主要是用来对方法形参就行输入校验

public Foo(Bar bar){
//校验bar参数,如果bar参数为null将引发异常,否则this.bar被赋值为bar参数
    this.bar = Objects.requireNonNull(bar);
}

6.3.3 String、 StringBuffer和StringBuilder类

String 类是不可变类,一旦创建不可改变
StringBuffer提供的append(),insert(),reverse(),setCharAt(),setLength()等方法可以改变这个字符串对象的字符序列。一旦确认最终想要的字符串可以调用toString()方法将其转变为一个String对象。
而StringBuilder和StringBuffer基本相似,不同的是StringBuffer是线程安全,StringBuilder是没有实现线程安全,所以性能略高,所有优先使用BufferBuiler~

package code;
import java.nio.charset.Charset;
public class StringTest{
    public static void main(String [] args)throws Exception{
        String str1 = new String();
        System.out.println(str1);

        byte[] b1 = new byte[]{1,2,3,‘a‘,‘b‘};
        String str2 = new String(b1,"US-ASCII");
        System.out.println(str2);

        String str3 = new String(b1,1,3);
        System.out.println(str3);

        String str4 = new String(b1,2,3,"US-ASCII");  
        System.out.println(str4);

        String str5 = new String(b1,"UTF-8");
        System.out.println(str5);

        char[] c1 = new char[]{‘a‘,‘b‘,‘v‘,‘e‘};
        String str6 = new String(c1,1,3);
        System.out.println(str6);

        String str7 = new String("I love You");
        System.out.println(str7);

        String s = new String("fkit.org");
        System.out.println("s.charAt(5):" + s.charAt(5));

        String s1 = new String("abcdefghijklmn");
        String s2 = new String("abcdefgh");
        String s3 = new String("abcdefgheww");
        System.out.println("s1.compareTo(s2):" + s1.compareTo(s2));//返回长度差
        System.out.println("s1.compareTo(s3):" + s1.compareTo(s3));//返回‘e‘-‘i‘的差

        String s4 = new String("I");
        String s5 = new String("love");
        System.out.println(s4.concat(s5));

        System.out.println(String.copyValueOf(c1));
        System.out.println(String.copyValueOf(c1,1,3));
        String t = new String("org");
        System.out.println("s.endsWith(t):" + s.endsWith(t));
    }
}

ab
a
ab
ab
bve
I love You
s.charAt(5):o
s1.compareTo(s2):6
s1.compareTo(s3):4
Ilove
abve
bve
s.endsWith(t):true

因为String是不可变的,所以会额外产生很多临时变量,使用StringBuffer和StringBuilder可以解决这个问题

package code;
public class StringBuilderTest{
    public static void main(String [] args){
        StringBuilder sb = new StringBuilder();
        System.out.println(sb);
        sb.append("java");
        System.out.println(sb);
        sb.insert(0,"hello ");
        System.out.println(sb);
        sb.replace(5,6,",");
        System.out.println(sb);
        sb.delete(4,6);
        System.out.println(sb);
        sb.reverse();
        System.out.println(sb);
        System.out.println("sb.length=" + sb.length());
        System.out.println("sb.capacity=" + sb.capacity());
        sb.setLength(5);
        System.out.println(sb);
    }

}

java
hello java
hello,java
helljava
avajlleh
sb.length=8
sb.capacity=16
avajl

capacity()的返回值比length()的大,因为它表示的是容量,而length()和setLength()表示的是长度

6.3.4 Math类

package code;
//import java.lang.Math;
public class MathTest{
    public static void main(String []args){
        //将弧度转换成角度
        System.out.println("Math.toDegrees(1.57):" + Math.toDegrees(1.57));
        //将角度转换成弧度
        System.out.println("Math.toRadians(90)" + Math.toRadians(90));
        //计算反余弦,返回的角度范围在0.0和pi之间
        System.out.println("Math.acos(1.2):" + Math.acos(1.2));
        //计算反正弦,返回的角度范围在-pi/2和pi/2之间
        System.out.println("Math.asin(0.8):"+Math.asin(0.8));
        //计算反正切,返回的角度范围在-pi/2和pi/2之间
        System.out.println("Math.atan(2.3):"+ Math.atan(2.3));
        //计算三角余弦,
        System.out.println("Math.cos(1.57):"+ Math.cos(1.57));
        //计算双角余弦
        System.out.println("Math.cosh(1.2):"+ Math.cosh(1.2));
        //计算三角正弦
        System.out.println("Math.sin(1.57):"+ Math.sin(1.57));
        //计算双角正弦
        System.out.println("Math.sinh(1.2):"+ Math.sinh(1.2));
        //计算三角正切
        System.out.println("Math.tan(1.57):"+ Math.tan(1.57));
        //计算双角正切
        System.out.println("Math.tanh(1.2):"+ Math.tanh(1.2));
        //将矩形坐标(x,y)转换成极坐标(r,thet)
        System.out.println("Math.atan2(0.1,0.2):"+ Math.atan2(0.1,0.2));
    /*-------下面是取整运算----------*/
        //取整,返回小于目标数的最大整数(floor地板,下面,小)
        System.out.println("Math.floor(-1.2):"+ Math.floor(-1.2));
        //取整,返回大于目标数的最大整数(ceil天花板,上面,大)
        System.out.println("Math.ceil(1.2):"+ Math.ceil(1.2));
        //四舍五入取整
        System.out.println("Math.round(2.3):"+ Math.round(2.3));
        /*------下面是乘方,开方,指数运算------*/
        //计算平方根
        System.out.println("Math.sqrt(9):"+ Math.sqrt(9));
        //计算立方根
        System.out.println("Math.cbrt(27):"+ Math.cbrt(27));
        //返回欧拉数e的n次幂
        System.out.println("Math.exp(2):"+ Math.exp(2));
        //返回sqrt(x2 + y2),没有中间溢出或下溢
        System.out.println("Math.hypot(4,4):"+ Math.hypot(4,4));
        //对两个参数进行余数运算
        System.out.println("Math.IEEEremainder(5,2):"+ Math.IEEEremainder(5,2));
        //乘方
        System.out.println("Math.pow(3,2):"+ Math.pow(3,2));
        //自然对数
        System.out.println("Math.log(12):"+ Math.log(12));
        //底数为10的对数
        System.out.println("Math.log10(9):"+ Math.log10(9));
        //返回参数与1之和的自然对数
        System.out.println("Math.log1p(9):"+ Math.log1p(9));
        /*---------下面是符号相关的运算-------*/
        //计算绝对值
        System.out.println("Math.abs(-4.5):"+ Math.abs(-4.5));
        //符号赋值,返回带有第二个浮点数符号的第一个浮点参数
        System.out.println("Math.copySign(1.2,-1.0):"+ Math.copySign(1.2,-1.0));
        //符号赋值,如果参数为0,则返回0,;如果参数大于0;返回1.0,小于0,返回-1.0
        System.out.println("Math.signum(2.3):"+ Math.signum(2.3));
        /*---------- 下面是大小相关的运算----------*/
        //找出最大值
        System.out.println("Math.max(2.3,4.5):"+ Math.max(2.3,4.5));
        //找出最小值
        System.out.println("Math.min(2.3,4.5):"+ Math.min(2.3,4.5));
        //返回第一个参数和第二个参数之间与第一个参数相邻的浮点数
        System.out.println("Math.nextAfter(1.2,1.0):"+ Math.nextAfter(1.2,1.0));
        //返回比目标数略大的浮点数
        System.out.println("Math.nextUp(1.2):"+ Math.nextUp(1.2));
        //返回一个伪随机数,该值大于0,小于1
        System.out.println("Math.random():"+ Math.random());

    }
}

Math.toDegrees(1.57):89.95437383553926
Math.toRadians(90)1.5707963267948966
Math.acos(1.2):NaN
Math.asin(0.8):0.9272952180016123
Math.atan(2.3):1.1606689862534056
Math.cos(1.57):7.963267107332633E-4
Math.cosh(1.2):1.8106555673243747
Math.sin(1.57):0.9999996829318346
Math.sinh(1.2):1.5094613554121725
Math.tan(1.57):1255.7655915007897
Math.tanh(1.2):0.8336546070121552
Math.atan2(0.1,0.2):0.4636476090008061
Math.floor(-1.2):-2.0
Math.ceil(1.2):2.0
Math.round(2.3):2
Math.sqrt(9):3.0
Math.cbrt(27):3.0
Math.exp(2):7.38905609893065
Math.hypot(4,4):5.656854249492381
Math.IEEEremainder(5,2):1.0
Math.pow(3,2):9.0
Math.log(12):2.4849066497880004
Math.log10(9):0.9542425094393249
Math.log1p(9):2.302585092994046
Math.abs(-4.5):4.5
Math.copySign(1.2,-1.0):-1.2
Math.signum(2.3):1.0
Math.max(2.3,4.5):4.5
Math.min(2.3,4.5):2.3
Math.nextAfter(1.2,1.0):1.1999999999999997
Math.nextUp(1.2):1.2000000000000002
Math.random():0.5786555949441676

6.3.5 ThreadLocalRandom与Random

ThreadLocalRandom是Random的增强版,在并发访问的环境下,使用ThreadLocalRandom可以减少多线程资源的竞争

package code;
import java.util.Random;
import java.util.Arrays;
public class RandomTest{
    public static void main(String[] args){
        Random ran = new Random();
        System.out.println("ran.nextBoolean:" + ran.nextBoolean());
        byte[] buffer = new byte[15];
        ran.nextBytes(buffer);
        System.out.println(Arrays.toString(buffer));
        System.out.println("ran.nextFloat:" + ran.nextFloat());
        System.out.println("ran.nextDouble:" + ran.nextDouble());
        System.out.println("ran.nextGaussian():" + ran.nextGaussian());
        System.out.println("ran.nextInt():" + ran.nextInt());
        System.out.println("ran.nextInt(26):" + ran.nextInt(26));
        System.out.println("ran.nextLong()"+ ran.nextLong());


    }
}

ran.nextBoolean:false
[-118, 120, -78, 79, 117, -76, 101, 29, -31, 110, -79, -27, 106, 61, 39]
ran.nextFloat:0.4258026
ran.nextDouble:0.17351229604540563
ran.nextGaussian():-1.690628772806466
ran.nextInt():-1305698100
ran.nextInt(26):16
ran.nextLong()8063485938025921173

如果这个类的两个实例是用同一个种子创建的,对它们以同样的顺序调用方法,则它们会产生相同的数字序列

package code;
import java.util.Random;
public class SeedTest{
    public static void main(String [] args){
        Random r1 = new Random(50);
        System.out.println("r1.nextBoolean():\t\t" + r1.nextBoolean());
        System.out.println("r1.nextInt():\t \t" + r1.nextInt());
        System.out.println("r1.nextDouble():\t\t"+ r1.nextDouble());
        System.out.println("r1.nextFloat():\t\t" + r1.nextFloat());
        System.out.println("----------------------");
        Random r2 = new Random(50);
        System.out.println("r2.nextBoolean():\t\t" + r2.nextBoolean());
        System.out.println("r2.nextInt():\t \t" + r2.nextInt());
        System.out.println("r2.nextDouble():\t\t"+ r2.nextDouble());
        System.out.println("r2.nextFloat():\t\t" + r2.nextFloat());
        System.out.println("----------------------");
        Random r3 = new Random(100);
        System.out.println("r3.nextBoolean():\t\t" + r3.nextBoolean());
        System.out.println("r3.nextInt():\t \t" + r3.nextInt());
        System.out.println("r3.nextDouble():\t\t"+ r3.nextDouble());
        System.out.println("r3.nextFloat():\t\t" + r3.nextFloat());
        System.out.println("----------------------");
    }
}

r1.nextBoolean(): true
r1.nextInt(): -1727040520
r1.nextDouble(): 0.6141579720626675
r1.nextFloat(): 0.6215813


r2.nextBoolean(): true
r2.nextInt(): -1727040520
r2.nextDouble(): 0.6141579720626675
r2.nextFloat(): 0.6215813


r3.nextBoolean(): true
r3.nextInt(): -1139614796
r3.nextDouble(): 0.19497605734770518
r3.nextFloat(): 0.66715956


只要两个对象的种子相同,而且方法的调用顺序相同,它们就会产生相同的序列~
所以并不是真正随机,只是伪随机
推荐使用当前时间作为Ramdom对象的种子

Random rand = new Random(System.currentTimeMillis());

ThreadLocalRandom与Random类似~

6.3.6 BigDecimal类

package code;
public class DoubleTest{
    public static void main(String [] args){
        System.out.println("0.05+0.01=" +(0.05+0.01));
        System.out.println("1.0-0.42=" + (1.0-0.42));
        System.out.println("4.015*100=" + (4.015*100));
        System.out.println("123.3/100" + (123.3/100));
    }
}

0.05+0.01=0.060000000000000005
1.0-0.42=0.5800000000000001
4.015*100=401.49999999999994
123.3/1001.2329999999999999

java的Double类型会发生精度丢失,所以Java提供了BigDecimal(double val)
,推荐使用BigDecimal(String val),因为结果是预知的,不是近似值。
如果必须使用double浮点数作为参数,则使用静态方法BigDecimal(double value)来创建

package code;
import java.math.BigDecimal;
public class BigDecimalTest{
    public static void main(String[]args){
        BigDecimal b1 = new BigDecimal("0.05");
        BigDecimal b2 = BigDecimal.valueOf(0.01);
        BigDecimal b3 = new BigDecimal(0.05);
        System.out.println(b1.add(b2));
        System.out.println(b1.subtract(b2));
        System.out.println(b1.multiply(b2));
        System.out.println(b1.divide(b2));
        System.out.println("----------------------------");
        System.out.println(b3.add(b2));
        System.out.println(b3.subtract(b2));
        System.out.println(b3.multiply(b2));
        System.out.println(b3.divide(b2));
    }
}

0.06
0.04
0.0005
5


0.06000000000000000277555756156289135105907917022705078125
0.04000000000000000277555756156289135105907917022705078125
0.0005000000000000000277555756156289135105907917022705078125
5.000000000000000277555756156289135105907917022705078125

package code;
import java.math.*;
import static java.math.BigDecimal.*;
public class Arith{
    public static int SCALE = 10;
    private Arith(){}
    public static double add(double d1 ,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.add(b2).doubleValue();
    }
    public static double sub(double d1 ,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.subtract(b2).doubleValue();
    }
    public static double mul(double d1 ,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.multiply(b2).doubleValue();
    }
    public static double div(double d1 ,double d2){
        BigDecimal b1 = BigDecimal.valueOf(d1);
        BigDecimal b2 = BigDecimal.valueOf(d2);
        return b1.divide(b2,SCALE,ROUND_HALF_EVEN).doubleValue();
    }
    public static double all(double d1,String a ,double d2){
        double dd =0;
        switch(a){
            case "+":
                dd = add(d1,d2);
                break;
            case "-":
                dd = sub(d1,d2);
                break;
            case "*":
                dd = mul(d1,d2);
                break;
            case "/":
                dd = div(d1,d2);
                break;  
            default:
                System.out.println("输入错误,请重新输入");
            break;
        }
        return dd;
    }
    public static void main(String[] args){
        System.out.println("0.5+0.1=" + add(0.5,0.1));
        System.out.println("0.5-0.1=" + sub(0.5,0.1));
        System.out.println("0.5*0.1=" + mul(0.5,0.1));
        System.out.println("0.5/0.1=" + div(0.5,0.1));
        System.out.println("0.5*0.1=" + all(0.5,"8",0.1));
    }
}

0.5+0.1=0.6
0.5-0.1=0.4
0.5*0.1=0.05
0.5/0.1=5.0
输入错误,请重新输入
0.5*0.1=0.0

常用类

标签:

原文地址:http://blog.csdn.net/u014270902/article/details/44019897

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!