• Java学习之路(五):常见的对象操作


    Object对象

    我们先来介绍一下API

    API(Application Programming Interface):应用程序编程接口

    Java API

    • 就是Java提供给我们使用的类,这些类将底层的实现封装起来
    • 我们不需要关心这些类是如何实现的,只需要学习这些类如何使用的就好

    Ojbect是超级类,任何类都会继承与Object类,你不写,父类默认是Object

    Object的概述

    • Object是类层次结构的根类
    • 所有类都直接或者间接的继承与Object类
    • Object类的构造方法: public Object()
    • 子类的构造方法默认访问的是父类的无参数构造方法

    Object的hashCode方法

    • Object有一个方法public int hashCode()
    • 方法返回一个哈希码值,默认情况下该方法会根据对象的地址来计算
    • 不同对象的hashCode()一般来说不会相同,但是同一个对象的hashCode值是肯定相同的
    • 注意:hashCode不是对象的实际地址值,可以理解为逻辑地址值
    public class test {
    
        public static void main(String[] args){
            StudentTest std1 = new StudentTest("null",11);
            StudentTest std2 = new StudentTest("null",12);
            StudentTest std3 = std1;
            System.out.println("std1:"+std1.hashCode());
            System.out.println("std2:"+std2.hashCode());
            System.out.println("std3:"+std3.hashCode());
        }
        
        
    }
    class StudentTest{
        String name;
        int age;
        public StudentTest(String name,int age){
            this.name = name;
            this.age = age;
        }
    }

    Object的getClass方法

     

    • 返回此object运行时类
    • 可以通过class类中的一个方法,获取对象的真实类的全名称
    package day15_nullnull;
    
    public class test {
    
        public static void main(String[] args){
            StudentTest std1 = new StudentTest("null",11);
            StudentTest std2 = new StudentTest("null",12);
            StudentTest std3 = std1;
            System.out.println(std1.getClass());
            System.out.println(std2.getClass());
            System.out.println(std3.getClass());
        }
        
        
    }
    class StudentTest{
        String name;
        int age;
        public StudentTest(String name,int age){
            this.name = name;
            this.age = age;
        }
    }

    Object类的toString方法

    •  toString方法返回此对象的字符串表示
    • 一般相当于:包名+@+Integer.toHexString(d.hashCode())
    • 但我们打印一个对象的时候,我们默认调用的就是toString方法,相当于Python中的__str__
    • 这个方法我们一个用于自定义字符串输出

    建议重写toString方法

    Object类的equals方法

    • 表示与其他对象是否相等
    • 默认情况下比较的是 对象的引用(地址)是否相同
    • 由于比较对象的引用没有意义,一般建议重写这个方法

    补充:==与equals方法的区别

    •  ==是一个比较云算法,即可以比较基本数据类型,也可以比较引用数据类型
      • 基本数据类型比较的是值,引用数据类型比较的是地址值
    • equals方法是一个方法,只能比较数据类型
      • 默认的equals和==比较引用数据类型无任何区别
      • 但是通过自定制,我们可以做到我们想要的比较结果

    Scanner类的一些介绍

     scanner是一个可以使用正则表达式来解析基本类型和字符串的简单文本扫描器

     scanner的构造方法:

      Scanner(InputStream source)

     System.in 介绍

    • System类下有一个静态的字段
    • public static final InputStream in    标准的输入流,对应着键盘录入

     Scanner的成员方法:

    比较重要的:

      hasNext..  判断是否还有下一个输入项,其中...可以是Int,Double等,如果需要判断是否包含字符串,则可以省略...

      next....  获取下一个输入项

    常用的:

    •  public int nextInt();   获取一个int类型的值
    • public String nextLine();  获取一个String类型的值,也就是字符串
    • 注意:如果要连用,最好使用一样的

    String类的介绍

     string的构造方法:

    •  public String()
    • public String(byte[] bytes)   把字节数组转化为字符串
    • public String(byte[] bytes,int index,int length)  把字节数组的一部分转化为字符串
    • public String(char[] value,int index,int count)  把字符数组的一部分转化为字符串
    • public String(String original)  初始化一个新创建的String对象,使其表示一个与参数相同的字符序列;就是说,新创建的字符串是该参数字符串的一个副本(有没有想到深拷贝)
    package day15_nullnull_01;
    
    public class null_String {
    
        public static void main(String[] args){
            String str1 = new String();
            System.out.println(str1);
            
            byte[] bytes1 = {97,98,99};
            String str2 = new String(bytes1);
            System.out.println(str2);
            
            byte[] bytes2 = {97,98,99,100,101,102,103};
            String str3 = new String(bytes2,1,4);
            System.out.println(str3);
            
            char[] chr = {'a','b','c'};
            String str4 = new String(chr);
            System.out.println(str4);
            
        }
        
        
    }

    下面来看几道面试题

    //1.判断定义为String类型的s1和s2是否相等
    String s1 = "abc";
    String s2 = "abc";
    System.out.println(s1 == s2);
    System.out.println(s1.equals(s2));
    true
    true
    //一个常量在内存中只存有一份
    答案
    //2.下面这句话在内存中创建了几个对象?
    String s1 = new String("abc");
    //总共创建了两个对象
    //常量池和堆区各有一个
    答案
    //3.判断定义为String类型的s1和s2是否相等
    String s1 = new String("abc");
    String s2 = "abc";
    
    System.out.println(s1 == s2);
    System.out.println(s1.equals(s2));
    不一样,一个在堆地址区,一个在常量区
    答案
    //4.判断定义为String类型的s1和s2是否相等
    String s1 = "a" + "b" + "c";
    String s2 = "abc";
    System.out.println(s1 == s2);
    System.out.println(s1.equals(s2));
    Java的常量优化机制
    其实在编辑的时候s1就已经是“abc”了
    答案
    //5.判断定义为String类型的s1和s2是否相等
    String s1 = "ab";
    String s2 = "abc";
    Strign s3 = s1 + "c";
    System.out.println(s3 == s2);
    System.out.println(s3.equals(s2));
    ==  的是 false
    equals 的是 true
    答案

    String类的判断功能

    • public boolean equals(Object anObject)     判断字符串是否一样
    • public boolean equalsIgnoreCase(String anotherString)  判断字符串是否一样,忽略大小写
    • public boolean contains(CharSequence s)  判断字符串是否包含那些字符
    • public boolean startsWith(String prefix)  判断字符串是否以什么开头
    • public boolean endsWith(String suffix) 判断字符串是否以什么结尾
    • public boolean isEmpty()  判断字符串是否为空字符串

    String类的获取功能

    • int length():获取字符串的长度
    • char charAt(int index):获取指定索引位置的字符
    • int indexOf(int ch):获取指定字符在此字符串第一次出现处的索引
    • int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引
    • int indexOf(int ch,int fromIndex):返回指定字符在此字符串中指定位置后第一次出现处的索引
    • int indexOf(String str,int fromIndex):返回指定字符串在此字符串中指定位置后第一次出现处的索引
    • lastIndexOf() 最后出现的位置
    • String substring(int start):从指定位置开始截取字符串,默认到未尾
    • String substring(int start,int end):从指定位置开始到指定位置结束截取字符图

    String类的转化功能

    • byte[] getBytes()   把字符串转化为字节数组
    • char[] toCharArray()  把字符串转化为字符数组
    • static String valueOf(char[] chs)  把字符数组转化为字符串
    • static String valueOf(int i)  把int类型的数据转化为字符串
    • 补充:String的valueOf方法可以把任意类型的数据转换成字符串
    • String toLowerCase()  把字符串转成小写
    • String toUpperCase()  把字符串转成大写
    • String concat(String str)  把字符串拼接,且只能拼接字符串。

    String类的其他的一些功能

    • public String replace(char oldChar,char newChar)   替换字符
    • public String replace(CharSequence target,CharSequence replacement)  替换字符串
    • Stringtrim(); 去除前后的空格
    • public int compareTo(String anotherString)   比较
    • public int compareToIgnoreCase(String str)   比较

    StringBuffer类的概述

    线程安全可变字符序列,一个类似与String的字符串缓冲区

    StringBuffer内部实现是字符串数组

    String和StringBuffer的区别:

    • String是一个不可变的字符序列
    • StringBuffer是一个可变的字符序列
    • StringBuffer线程安全,可以加锁

    StringBuffer类的构造方法

    • public StringBuffer()    构造一个其中不带字符的字符串缓冲区,初始容量为16个字符
    • public StringBuffer(int capacity)  构造一个不带字符,但是具有指定初始容量的字符串缓冲区
    • public StringBuffer(CharSequence seq)  构造一个字符串缓冲区,它包含与指定的CharSequence相同的字符
    • public StringBuffer(String str)  构造一个字符串缓冲区,并将其内容初始化为指定的字符串内容

    StringBuffer的方法

    • public int capacity()   返回当前的容量。(理论值?)
    • public int length()    返回长度(字符数)  (实际值)

    StringBuffer的添加功能

    • public StringBuffer append(String str)   可以把任意类型数据添加到字符缓冲区,并返回一个字符缓冲区本身
    • public StringBuffer insert(int offset,String str)  在指定位置把任意类型的数据插入到字符缓冲区中,并返回字符串缓冲区本身

    StringBuffer的删除功能

    • public StringBuffer deleteCharAt(int index)    删除指定位置的字符,并返回本身
    • public StringBuffer delete(int start,int end)  删除从指定位置开始到指定位置结束的内容,并返回本身

    StringBuffer的替换和翻转功能

    • public StringBuffer replace(int start,int end,String str)   从start开始到end用str进行替换
    • public StringBuffer reverse()    字符串的翻转

    StringBuffer的截取

    • public String substring(int start)   从指定位置截取到末尾
    • public String substring(int start,int end)  截取从指定位置开始到结束位置,包括开始位置,不包括结束位置
    • 注意:之前的返回值都是StringBuffer本事,这次返回的是String

    String和StringBuffer之间的转换

    String===>StringBuffer

    1.通过构造方法,在创建StringBuffer时候,就将String当做参数传入

    2.通过apped()方法

    StringBuffer===>String

    1.同过构造方法

    2.通过StringBuffer的toString()方法

    3.通过subString(start,end)切片的方法

    补充:

     1.StringBuffer和StringBuilder的区别

    • StringBuffer是jdk1.0版本的,是线程安全的,也是效率低下的
    • StringBuilder是jdk1.5版本的,是线程不安全的,但也是效率高的

    2.String和StringBuffer以及StringBuilder的区别

    • String是一个不可变的字符序列
    • StringBuffer和StringBuilder是一个可变的字符序列

     Arrays类的概述和使用方法

    概述:

    • 针对数组进行操作的工具类
    • 提供的方法都是通过类方法调用,因为构造方法私有化
    • 提供了排序、查找等功能,具体请看API文档

    一些主要的方法

    • public static String toString(int[] a)    传入一个数组,返回一个字符串,也就是将数组转化为字符串
    • public static void sort(int[] a)     传入一个数组,进行一个排序
    • public static int binarySearch(int[] a,int key)   这个就是内置的二分查找的方法
    package day16_nullnull;
    
    import java.util.Arrays;
    
    public class null04_Arrays {
    
        public static void main(String[] args) {
            int[] arr = {11,88,55,44,66,33,22};
            
            //1.public static String toString(int[] a)
            System.out.println(Arrays.toString(arr));
            
            //2.public static void sort(int[] a)
            Arrays.sort(arr);
            System.out.println(Arrays.toString(arr));
            
            //3.public static int binarySearch(int[] a,int key)
            int result = Arrays.binarySearch(arr,66);
            System.out.println(result);
            
        }
    
    }

    注意:二分查找时,如果它包含在数组中,则返回搜索键的索引;否则返回的是(-(插入点)-1)

     Math类的概述和简单的使用方法

     Math类包含了用于执行基本数学运算的方法。

     重要的:

    • public static int abs(int a)      返回绝对值
    • public static double ceil(double a)        取整,向大了取
    • public static double floor(double a)       取整,向小了取
    • public static int max(int a,int b)              返回两个中 大 的一个
    • public static double pow(double a,double b)      求乘方的运算
    • public static double random()                   随机数嘛
    • public static int round(float a)                  四舍五入
    • public static double sqrt(double a)        求平方根的运算
    package day16_nullnull;
    
    //Math类的一些主要用法
    
    public class null05_Math {
    
        public static void main(String[] args) {
            System.out.println("abs:"+Math.abs(-3.14));
            System.out.println("ceil:"+Math.ceil(3.14));
            System.out.println("floor:"+Math.floor(3.14));
            System.out.println("Max:"+Math.max(5.5,10.1));
            System.out.println("pow:"+Math.pow(5,2));
            System.out.println("random:"+Math.random());
            System.out.println("round:"+Math.round(3.14));
            System.out.println("sqrt:"+Math.sqrt(16));
    
        }
    
    }

    Random类的概述和简单使用

      一般用于产生随机数使用,特殊的,如果用相同的种子创建两个Random实例,则每个实例进行相同的方法调用序列,他们将生成并返回相同的数字序列。

    Random的构造方法

    • public Random()
    • public Random(long seed)     这就是那个特殊的传入种子的

    Random的一些方法

    • public int nextInt()
    • public int nextInt(int bound)

     另:

    System类的概述和简单使用

     注意:

     

    System类是不能被实例话的。

    一些重要的成员方法:

    • public static void gc()      我们手动运行一次垃圾回收
    • public static void exit(int status)             退出
    • public static long currentTimeMillis()     返回以毫秒为单位的时间,从1970.1.1午夜开始算起
    • public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)       copy一个数组的某一部分,到另一个数组

     BigInteger类的概述和简单的使用方法

    可以让超过Integer范围内的数据进行运算

    eg:

    package lesson1;
    
    public class null01_BigInteger {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int a = Integer.MAX_VALUE;  //获取到int的最大值
            int b = Integer.MAX_VALUE;
            System.out.println("a:"+a);
            System.out.println(a+b);       //绝对超出了int的最大范围
        }
    
    }

    这时候就该是我么的BigInteger登场了

    package lesson1;
    
    import java.math.BigInteger;
    
    public class null01_BigInteger {
    
        public static void main(String[] args) {
            
            BigInteger a = new BigInteger("2147483647");
            BigInteger b = new BigInteger("2147483647");
            System.out.println(a.add(b));
            
        }
    
    }

     结果:

    4294967294

    BigInteger的一些成员方法

    • public BigInteger add(BigInteger val)    与另一个BigInteger相加
    • public BigInteger subtract(BigInteger val)    相减运算
    • public BigInteger multiply(BigInteger val)    乘法运算
    • public BigInteger divide(BigInteger val)    除法运算
    • public BigInteger[] divideAndRemainder(BigInteger val)     求模运算,返回一个Biginteger的数组
    package lesson1;
    
    import java.math.BigInteger;
    
    public class null01_BigInteger {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            
            BigInteger bi1 = new BigInteger("4294967294");
            BigInteger bi2 = new BigInteger("42949672");
            // % 求模
            BigInteger[] bis = bi1.divideAndRemainder(bi2);
            System.out.println("商:" + bis[0]);
            System.out.println("余数:" + bis[1]);
            System.out.println(bis.getClass());
            System.out.println(bis.length);
            
        }
    
    }

    结果:

    商:100
    余数:94
    class [Ljava.math.BigInteger;
    2

    BigDecimal类的概述和简单使用

    由于在运算的时候,float类型和double很容易会丢失精度。所以,为了能精确的表示、计算浮点数,有了BigDecimal类

    构造方法

    • public BigDecimal(String val)

    成员方法

    • public BigDecimal add(BigDecimal augend)
    • public BigDecimal subtract()
    • public BigDecimal mutiply()
    • public BigDecimal divide()
    • 和上面的BigInteger用法类似

    Date类的概述和简单使用

    Date表示特定的时间,精确到了毫秒

    构造方法

    • public Date()
    • public Date(long date)

    成员方法

    • public long getTime()       返回自1970.1.1 0.0.0.0 以来的时间戳
    • public void setTime(long time)    设置一个时间,表示从1970.1.1开始多少毫秒后的一个时间戳

    SimpleDateFormat类的概述和简单使用

    DateFormat是日期/时间格式化子类的  抽象类  ,用于格式化并且解析日期或时间。

    DateFormat是一个抽象类,所以我们使用它的子类SimpleDateFormat。

    SimpleDateFormat的构造方法

    • public SimpleDateFormat()
    • public SimpleDateFormat(String pattern)

    成员方法

    • public final String format(Date date)
    • public Date parse(String source)
    package lesson2;
    
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    //利用SimpleDateFormat计算一些自己出生了多长时间
    
    
    public class null01_SimpleDateFormat {
    
        public static void main(String[] args) throws ParseException {
            // TODO Auto-generated method stub
    
            String birthday = "1998-10-11";
            String today = "2018-7-19";
            
            //转化为Date
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday_date = fmt.parse(birthday);
            Date today_date = fmt.parse(today);
            
            long t = today_date.getTime() - birthday_date.getTime();
            System.out.println(t/1000/60/60/24);
        }
    
    }

    Caledar类的概述和简单使用

    Calendar类是一个  抽象类  ,也就是说我们不能直接实例化。它为特定的瞬间与与一组诸如YEAR、MONTH、DAY_OF_MONTH、HOUR等日历字段之间的转化提供了方法,并为操作日历字段提供了方法

    我们一般使用的都是它的子类:GregorlanCalendar,我们通过调用getInstance方法实现

    成员方法:

    • public static Calendar getInstance()
    • public int get(int field)

    注意:

      获取月份是0:1月,1:二月.....

      1:周日,2:周一.....

    package lesson3;
    
    import java.util.Calendar;
    
    //Calendar类的add()和set()方法的使用
    
    
    public class null01_Calendar {
    
        public static void main(String[] args) {
            //add用法
            Calendar c = Calendar.getInstance();
            c.add(Calendar.YEAR, 1);
            System.out.println(c.get(Calendar.YEAR));
            
            c.add(Calendar.MONTH, -10);   //月份每轮是0-11
            System.out.println(c.get(Calendar.MONTH));
            
            //set用法
            c.set(1998,10,11);
            System.out.println(c.get(Calendar.YEAR));
    
    
        }
    
    }

    结果:

    2019
    8
    1998
    package lesson3;
    //小练手:判断某一年是不是闰年
    import java.util.Calendar;
    
    public class null02_Calendar {
    
        public static void main(String[] args) {
            int year = 2016;//指定想要判断的年份
            
            //创建Calendar
            Calendar c = Calendar.getInstance();
            
            c.set(year,2,1);
            c.add(Calendar.DAY_OF_MONTH,-1);
            int co = c.get(Calendar.DATE);
            System.out.println(co);
            //29不就是闰年了
    
        }
    
    }
    小练手:判断某一年是不是闰年
  • 相关阅读:
    效能分析
    个人项目词频统计2
    PSP 进度条 柱状图 饼状图
    四人小组项目
    结对编程
    品评历届学生作品
    构建之法终于到手了
    补上周一的进度条进度条:
    燃尽图
    scrum站立会议
  • 原文地址:https://www.cnblogs.com/smiling-crying/p/9326933.html
Copyright © 2020-2023  润新知