黑马程序员--Java常见对象

——- android培训java培训、期待与您交流! ———-

API

API (Application Programming Interface)
应用程序编程接口
JDK提供给我们的一些提高编程效率的java类。

Object

类 Object 是类层次结构的根类。每个类都使用 Object 作为超类。
每个类都直接或者间接的继承自Object类。

Object类的方法
public int hashCode():返回该对象的哈希码值。

  • 注意:哈希值是根据哈希算法计算出来的一个值,这个值和地址值有关,但是不是实际地址值。可以理解为地址值。

public final Class getClass():返回此 Object 的运行时类
Class类的方法:
public String getName():以 String 的形式返回此 Class 对象所表示的实体
Object类的构造方法有一个,并且是无参构造

public class Student {

}

// 测试类
class StudentTest {
    public static void main(String[] args) {
        Student s1 = new Student();
        System.out.println(s1.hashCode()); // 11299397
        Student s2 = new Student();
        System.out.println(s2.hashCode());// 24446859
        Student s3 = s1;
        System.out.println(s3.hashCode()); // 11299397
        System.out.println("-----------");

        Student s = new Student();
        Class c = s.getClass();
        String str = c.getName();
        System.out.println(str); // cn.itcast_01.Student

        // 链式编程
        String str2 = s.getClass().getName();
        System.out.println(str2);
    }
}

public String toString():返回该对象的字符串表示。

  • 注意: 直接输出一个对象的名称,其实就是调用该对象的toString()方法。
//学生类
public class Student {
    private String name;
    private int age;

    public Student() {
        super();
    }

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
}
//测试类
public class StudentDemo {
    public static void main(String[] args) {
        Student s = new Student();
        System.out.println(s.hashCode());
        System.out.println(s.getClass().getName());
        System.out.println("--------------------");
        System.out.println(s.toString());
        System.out.println("--------------------");
        System.out.println(s.getClass().getName() + '@'
                + Integer.toHexString(s.hashCode()));

        System.out.println(s.toString());

        // 直接输出对象的名称
        System.out.println(s);
    }
}

public boolean equals(Object obj):指示其他某个对象是否与此对象“相等”。
这个方法,默认情况下比较的是地址值。比较地址值一般来说意义不大,所以我们要重写该方法。一般都是用来比较对象的成员变量值是否相同。
重写的代码优化:提高效率,提高程序的健壮性。

==和equals的区别

  • ==:
    基本类型:比较的就是值是否相同
    引用类型:比较的就是地址值是否相同

  • equals:
    引用类型:默认情况下,比较的是地址值。
    不过,我们可以根据情况自己重写该方法。一般重写都是自动生成,比较对象的成员变量值是否相同

//学生类
public class Student {
    private String name;
    private int age;

    public Student() {
        super();
    }

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
}
//测试类
public class StudentDemo {
    public static void main(String[] args) {
        Student s1 = new Student("李延旭", 21);
        Student s2 = new Student("李延旭", 21);
        System.out.println(s1 == s2); // false
        Student s3 = s1;
        System.out.println(s1 == s3);// true
        System.out.println("---------------");

        System.out.println(s1.equals(s2)); // obj = s2; //false
        System.out.println(s1.equals(s1)); // true
        System.out.println(s1.equals(s3)); // true
        Student s4 = new Student("周杰伦",30);
        System.out.println(s1.equals(s4)); //false

        Demo d = new Demo();
        System.out.println(s1.equals(d)); //ClassCastException

    }
}

class Demo {}

protected void finalize():当垃圾回收器确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。用于垃圾回收,但是什么时候回收不确定。

protected Object clone():创建并返回此对象的一个副本。需要重写该方法

Cloneable:此类实现了 Cloneable 接口,以指示 Object.clone() 方法可以合法地对该类实例进行按字段复制。
这个接口是标记接口,告诉我们实现该接口的类就可以实现对象的复制了。

//学生类

public class Student implements Cloneable {
    private String name;
    private int age;

    public Student() {
        super();
    }

    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
测试类
public class StudentDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        //创建学生对象
        Student s = new Student();
        s.setName("李延旭");
        s.setAge(21);

        //克隆学生对象
        Object obj = s.clone();
        Student s2 = (Student)obj;
        System.out.println("---------");

        System.out.println(s.getName()+"---"+s.getAge());
        System.out.println(s2.getName()+"---"+s2.getAge());

        //以前的做法
        Student s3 = s;
        System.out.println(s3.getName()+"---"+s3.getAge());
        System.out.println("---------");

        //其实是有区别的
        s3.setName("周杰伦");
        s3.setAge(30);
        System.out.println(s.getName()+"---"+s.getAge());
        System.out.println(s2.getName()+"---"+s2.getAge());
        System.out.println(s3.getName()+"---"+s3.getAge());

    }
}

Scanner

概述
用于接收键盘录入数据。

步骤
A:导包
B:创建对象
C:调用方法

构造方法
InputStream is = System.in;
Scanner(InputStream source)

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        // 创建对象
        Scanner sc = new Scanner(System.in);

        int x = sc.nextInt();

        System.out.println("x:" + x);
    }
}

基本方法格式

A:hasNextXxx() 判断是否是某种类型的
B:nextXxx() 返回某种类型的元素

用int类型的方法举例
public boolean hasNextInt()
public int nextInt()

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        // 创建对象
        Scanner sc = new Scanner(System.in);

        // 获取数据
        if (sc.hasNextInt()) {
            int x = sc.nextInt();
            System.out.println("x:" + x);
        } else {
            System.out.println("你输入的数据有误");
        }
    }
}

常用的两个方法:
public int nextInt():获取一个int类型的值
public String nextLine():获取一个String类型的值
此处会出现一个问题
先获取一个数值,在获取一个字符串,会出现问题。
主要原因:就是那个换行符号的问题。

解决方法
A:先获取一个数值后,在创建一个新的键盘录入对象获取字符串。
B:把所有的数据都先按照字符串获取,然后要什么,你就对应的转换为什么。

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        // 创建对象
        Scanner sc = new Scanner(System.in);

        // 获取两个int类型的值
        // int a = sc.nextInt();
        // int b = sc.nextInt();
        // System.out.println("a:" + a + ",b:" + b);
        // System.out.println("-------------------");

        // 获取两个String类型的值
        // String s1 = sc.nextLine();
        // String s2 = sc.nextLine();
        // System.out.println("s1:" + s1 + ",s2:" + s2);
        // System.out.println("-------------------");

        // 先获取一个字符串,在获取一个int值
        // String s1 = sc.nextLine();
        // int b = sc.nextInt();
        // System.out.println("s1:" + s1 + ",b:" + b);
        // System.out.println("-------------------");

        // 先获取一个int值,在获取一个字符串
        // int a = sc.nextInt();
        // String s2 = sc.nextLine();
        // System.out.println("a:" + a + ",s2:" + s2);
        // System.out.println("-------------------");

        int a = sc.nextInt();
        Scanner sc2 = new Scanner(System.in);
        String s = sc2.nextLine();
        System.out.println("a:" + a + ",s:" + s);
    }
}

String

字符串:就是由多个字符组成的一串数据。也可以看成是一个字符数组。

通过查看API,我们可以知道
A:字符串字面值”abc”也可以看成是一个字符串对象。
B:字符串是常量,一旦被赋值,就不能被改变。

字符串的特点
A:字符串一旦被赋值,就不能改变。

  • 注意:这里指的是字符串的内容不能改变,而不是引用不能改变。

B:字面值作为字符串对象和通过构造方法创建对象的不同

构造方法
public String():空构造
public String(byte[] bytes):把字节数组转成字符串
public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
public String(char[] value):把字符数组转成字符串
public String(char[] value,int index,int count):把字符数组的一部分转成字符串
public String(String original):把字符串常量值转成字符串

字符串的方法:
public int length():返回此字符串的长度。

public class StringDemo {
    public static void main(String[] args) {
        // public String():空构造
        String s1 = new String();
        System.out.println("s1:" + s1);
        System.out.println("s1.length():" + s1.length());
        System.out.println("--------------------------");

        // public String(byte[] bytes):把字节数组转成字符串
        byte[] bys = { 97, 98, 99, 100, 101 };
        String s2 = new String(bys);
        System.out.println("s2:" + s2);
        System.out.println("s2.length():" + s2.length());
        System.out.println("--------------------------");

        // public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串
        // 我想得到字符串"bcd"
        String s3 = new String(bys, 1, 3);
        System.out.println("s3:" + s3);
        System.out.println("s3.length():" + s3.length());
        System.out.println("--------------------------");

        // public String(char[] value):把字符数组转成字符串
        char[] chs = { 'a', 'b', 'c', 'd', 'e', '爱', '林', '亲' };
        String s4 = new String(chs);
        System.out.println("s4:" + s4);
        System.out.println("s4.length():" + s4.length());
        System.out.println("--------------------------");

        // public String(char[] value,int index,int count):把字符数组的一部分转成字符串
        String s5 = new String(chs, 2, 4);
        System.out.println("s5:" + s5);
        System.out.println("s5.length():" + s5.length());
        System.out.println("--------------------------");

        // public String(String original):把字符串常量值转成字符串
        String s6 = new String("abcde");
        System.out.println("s6:" + s6);
        System.out.println("s6.length():" + s6.length());
        System.out.println("--------------------------");

        // 字符串字面值"abc"也可以看成是一个字符串对象。
        String s7 = "abcde";
        System.out.println("s7:" + s7);
        System.out.println("s7.length():" + s7.length());
    }
}

字符串的功能

// 判断功能

/*
 * String类的判断功能: boolean equals(Object obj):比较字符串的内容是否相同,区分大小写 boolean
 * equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写 boolean contains(String
 * str):判断大字符串中是否包含小字符串 boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
 * boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾 boolean isEmpty():判断字符串是否为空。
 * 
 * 注意: 字符串内容为空和字符串对象为空。 String s = ""; String s = null;
 */
public class StringDemo {
    public static void main(String[] args) {
        // 创建字符串对象
        String s1 = "helloworld";
        String s2 = "helloworld";
        String s3 = "HelloWorld";

        // boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
        System.out.println("equals:" + s1.equals(s2));
        System.out.println("equals:" + s1.equals(s3));
        System.out.println("-----------------------");

        // boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
        System.out.println("equals:" + s1.equalsIgnoreCase(s2));
        System.out.println("equals:" + s1.equalsIgnoreCase(s3));
        System.out.println("-----------------------");

        // boolean contains(String str):判断大字符串中是否包含小字符串
        System.out.println("contains:" + s1.contains("hello"));
        System.out.println("contains:" + s1.contains("hw"));
        System.out.println("-----------------------");

        // boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
        System.out.println("startsWith:" + s1.startsWith("h"));
        System.out.println("startsWith:" + s1.startsWith("hello"));
        System.out.println("startsWith:" + s1.startsWith("world"));
        System.out.println("-----------------------");

        // 练习:boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾这个自己玩

        // boolean isEmpty():判断字符串是否为空。
        System.out.println("isEmpty:" + s1.isEmpty());

        String s4 = "";
        String s5 = null;
        System.out.println("isEmpty:" + s4.isEmpty());
        // NullPointerException
        // s5对象都不存在,所以不能调用方法,空指针异常
        System.out.println("isEmpty:" + s5.isEmpty());
    }
}

// 获取功能

/*
 * String类的获取功能 int length():获取字符串的长度。 char charAt(int index):获取指定索引位置的字符 int
 * indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。 为什么这里是int类型,而不是char类型?
 * 原因是:'a'和97其实都可以代表'a' int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。 int
 * indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。 int indexOf(String
 * str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。 String substring(int
 * start):从指定位置开始截取字符串,默认到末尾。 String substring(int start,int
 * end):从指定位置开始到指定位置结束截取字符串。
 */
public class StringDemo {
    public static void main(String[] args) {
        // 定义一个字符串对象
        String s = "helloworld";

        // int length():获取字符串的长度。
        System.out.println("s.length:" + s.length());
        System.out.println("----------------------");

        // char charAt(int index):获取指定索引位置的字符
        System.out.println("charAt:" + s.charAt(7));
        System.out.println("----------------------");

        // int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。
        System.out.println("indexOf:" + s.indexOf('l'));
        System.out.println("----------------------");

        // int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。
        System.out.println("indexOf:" + s.indexOf("owo"));
        System.out.println("----------------------");

        // int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。
        System.out.println("indexOf:" + s.indexOf('l', 4));
        System.out.println("indexOf:" + s.indexOf('k', 4)); // -1
        System.out.println("indexOf:" + s.indexOf('l', 40)); // -1
        System.out.println("----------------------");

        // 自己练习:int indexOf(String str,int
        // fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。

        // String substring(int start):从指定位置开始截取字符串,默认到末尾。包含start这个索引
        System.out.println("substring:" + s.substring(5));
        System.out.println("substring:" + s.substring(0));
        System.out.println("----------------------");

        // String substring(int start,int
        // end):从指定位置开始到指定位置结束截取字符串。包括start索引但是不包end索引
        System.out.println("substring:" + s.substring(3, 8));
        System.out.println("substring:" + s.substring(0, s.length()));
    }
}

// 转换功能

/*
 * 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):把字符串拼接。
 */
public class StringDemo {
    public static void main(String[] args) {
        // 定义一个字符串对象
        String s = "JavaSE";

        // byte[] getBytes():把字符串转换为字节数组。
        byte[] bys = s.getBytes();
        for (int x = 0; x < bys.length; x++) {
            System.out.println(bys[x]);
        }
        System.out.println("----------------");

        // char[] toCharArray():把字符串转换为字符数组。
        char[] chs = s.toCharArray();
        for (int x = 0; x < chs.length; x++) {
            System.out.println(chs[x]);
        }
        System.out.println("----------------");

        // static String valueOf(char[] chs):把字符数组转成字符串。
        String ss = String.valueOf(chs);
        System.out.println(ss);
        System.out.println("----------------");

        // static String valueOf(int i):把int类型的数据转成字符串。
        int i = 100;
        String sss = String.valueOf(i);
        System.out.println(sss);
        System.out.println("----------------");

        // String toLowerCase():把字符串转成小写。
        System.out.println("toLowerCase:" + s.toLowerCase());
        System.out.println("s:" + s);
        // System.out.println("----------------");
        // String toUpperCase():把字符串转成大写。
        System.out.println("toUpperCase:" + s.toUpperCase());
        System.out.println("----------------");

        // String concat(String str):把字符串拼接。
        String s1 = "hello";
        String s2 = "world";
        String s3 = s1 + s2;
        String s4 = s1.concat(s2);
        System.out.println("s3:" + s3);
        System.out.println("s4:" + s4);
    }
}

// 其他功能

/*
 * String类的其他功能:
 * 
 * 替换功能: String replace(char old,char new) String replace(String old,String new)
 * 
 * 去除字符串两空格 String trim()
 * 
 * 按字典顺序比较两个字符串 int compareTo(String str) int compareToIgnoreCase(String str)
 */
public class StringDemo {
    public static void main(String[] args) {
        // 替换功能
        String s1 = "helloworld";
        String s2 = s1.replace('l', 'k');
        String s3 = s1.replace("owo", "ak47");
        System.out.println("s1:" + s1);
        System.out.println("s2:" + s2);
        System.out.println("s3:" + s3);
        System.out.println("---------------");

        // 去除字符串两空格
        String s4 = " hello world  ";
        String s5 = s4.trim();
        System.out.println("s4:" + s4 + "---");
        System.out.println("s5:" + s5 + "---");

        // 按字典顺序比较两个字符串
        String s6 = "hello";
        String s7 = "hello";
        String s8 = "abc";
        String s9 = "xyz";
        System.out.println(s6.compareTo(s7));// 0
        System.out.println(s6.compareTo(s8));// 7
        System.out.println(s6.compareTo(s9));// -16
    }
}

StringBuffer

线程安全的可变字符串。
用字符串做拼接,比较耗时并且也耗内存,而这种拼接操作又是比较常见的,为了解决这个问题,Java就提供了一个字符串缓冲区类。StringBuffer供我们使用。

StringBuffer和String的区别
前者长度和内容可变,后者不可变。
如果使用前者做字符串的拼接,不会浪费太多的资源。

StringBuffer的构造方法

  • A:StringBuffer()
  • B:StringBuffer(int size)
  • C:StringBuffer(String str)

StringBuffer的方法

  • public int capacity():返回当前容量。 理论值
  • public int length():返回长度(字符数)。 实际值
public class StringBufferDemo {
    public static void main(String[] args) {
        // public StringBuffer():无参构造方法
        StringBuffer sb = new StringBuffer();
        System.out.println("sb:" + sb);
        System.out.println("sb.capacity():" + sb.capacity());
        System.out.println("sb.length():" + sb.length());
        System.out.println("--------------------------");

        // public StringBuffer(int capacity):指定容量的字符串缓冲区对象
        StringBuffer sb2 = new StringBuffer(50);
        System.out.println("sb2:" + sb2);
        System.out.println("sb2.capacity():" + sb2.capacity());
        System.out.println("sb2.length():" + sb2.length());
        System.out.println("--------------------------");

        // public StringBuffer(String str):指定字符串内容的字符串缓冲区对象
        StringBuffer sb3 = new StringBuffer("hello");
        System.out.println("sb3:" + sb3);
        System.out.println("sb3.capacity():" + sb3.capacity());
        System.out.println("sb3.length():" + sb3.length());
    }
}

StringBuffer的功能

//添加功能

/*
 * StringBuffer的添加功能:
 * public StringBuffer append(String str):可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
 * 
 * public StringBuffer insert(int offset,String str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();

        // public StringBuffer append(String str)
        // StringBuffer sb2 = sb.append("hello");
        // System.out.println("sb:" + sb);
        // System.out.println("sb2:" + sb2);
        // System.out.println(sb == sb2); // true

        // 一步一步的添加数据
        // sb.append("hello");
        // sb.append(true);
        // sb.append(12);
        // sb.append(34.56);

        // 链式编程
        sb.append("hello").append(true).append(12).append(34.56);
        System.out.println("sb:" + sb);

        // public StringBuffer insert(int offset,String
        // str):在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身
        sb.insert(5, "world");
        System.out.println("sb:" + sb);
    }
}

// 删除功能

/*
 * StringBuffer的删除功能 public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
 * public StringBuffer delete(int start,int end):删除从指定位置开始指定位置结束的内容,并返回本身
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建对象
        StringBuffer sb = new StringBuffer();

        // 添加功能
        sb.append("hello").append("world").append("java");
        System.out.println("sb:" + sb);

        // public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回本身
        // 需求:我要删除e这个字符,肿么办?
        // sb.deleteCharAt(1);
        // 需求:我要删除第一个l这个字符,肿么办?
        // sb.deleteCharAt(1);

        // public StringBuffer delete(int start,int
        // end):删除从指定位置开始指定位置结束的内容,并返回本身
        // 需求:我要删除world这个字符串,肿么办?
        // sb.delete(5, 10);

        // 需求:我要删除所有的数据
        sb.delete(0, sb.length());

        System.out.println("sb:" + sb);
    }
}

// 替换功能

/*
 * StringBuffer的替换功能: public StringBuffer replace(int start,int end,String
 * str):从start开始到end用str替换
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();

        // 添加数据
        sb.append("hello");
        sb.append("world");
        sb.append("java");
        System.out.println("sb:" + sb);

        // public StringBuffer replace(int start,int end,String
        // str):从start开始到end用str替换
        // 需求:我要把world这个数据替换为"节日快乐"
        sb.replace(5, 10, "节日快乐");
        System.out.println("sb:" + sb);
    }
}

// 反转功能

/*
 * StringBuffer的反转功能: public StringBuffer reverse()
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();

        // 添加数据
        sb.append("的念来过倒是猪");
        System.out.println("sb:" + sb);

        // public StringBuffer reverse()
        sb.reverse();
        System.out.println("sb:" + sb);
    }
}

// 截取功能

/*
 * StringBuffer的截取功能 public String substring(int start) public String
 * substring(int start,int end)
 */
public class StringBufferDemo {
    public static void main(String[] args) {
        // 创建字符串缓冲区对象
        StringBuffer sb = new StringBuffer();

        // 添加元素
        sb.append("hello").append("world").append("java");
        System.out.println("sb:" + sb);

        // 截取功能
        // public String substring(int start)
        String s = sb.substring(5);
        System.out.println("s:" + s);
        System.out.println("sb:" + sb);

        // public String substring(int start,int end)
        String ss = sb.substring(5, 10);
        System.out.println("ss:" + ss);
        System.out.println("sb:" + sb);
    }
}

String,StringBuffer,StringBuilder的区别?

  • A:String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的。
  • B:StringBuffer是同步的,数据安全,效率低;StringBuilder是不同步的,数据不安全,效率高

StringBuffer和数组的区别
二者都可以看出是一个容器,装其他的数据。
但是,StringBuffer的数据最终是一个字符串数据。
而数组可以放置多种数据,但必须是同一种数据类型的。

数组高级以及Arrays

排序
A:冒泡排序
相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处。同理,其他的元素就可以排好。

public static void bubbleSort(int[] arr) {
    for(int x=0; x<arr.length-1; x++) {
        for(int y=0; y<arr.length-1-x; y++) {
            if(arr[y] > arr[y+1]) {
                int temp = arr[y];
                arr[y] = arr[y+1];
                arr[y+1] = temp;
            }
        }
    }
}

B:选择排序

  • 把0索引的元素,和索引1以后的元素都进行比较,第一次完毕,最小值出现在了0索引。同理,其他的元素就可以排好。
public static void selectSort(int[] arr) {
    for(int x=0; x<arr.length-1; x++) {
        for(int y=x+1; y<arr.length; y++) {
            if(arr[y] < arr[x]) {
                int temp = arr[x];
                arr[x] = arr[y];
                arr[y] = temp;
            }
        }
    }
}

查找
A:基本查找
针对数组无序的情况

public static int getIndex(int[] arr,int value) {
    int index = -1;

    for(int x=0; x<arr.length; x++) {
        if(arr[x] == value) {
            index = x;
            break;
        }
    }

    return index;
}

B:二分查找(折半查找)
针对数组有序的情况(千万不要先排序,在查找)

public static int binarySearch(int[] arr,int value) {
    int min = 0;
    int max = arr.length-1;
    int mid = (min+max)/2;

    while(arr[mid] != value) {
        if(arr[mid] > value) {
            max = mid - 1;
        }else if(arr[mid] < value) {
            min = mid + 1;
        }

        if(min > max) {
            return -1;
        }

        mid = (min+max)/2;
    }

    return mid;
}

Arrays工具类

A:是针对数组进行操作的工具类。包括排序和查找等功能。
B:要掌握的方法
把数组转成字符串:
排序:
二分查找:

import java.util.Arrays;

/*
 * 1:public static String toString(int[] a) 把数组转成字符串
 * 2:public static void sort(int[] a) 对数组进行排序
 * 3:public static int binarySearch(int[] a,int key) 二分查找
 */
public class ArraysDemo {
    public static void main(String[] args) {
        // 定义一个数组
        int[] arr = { 24, 69, 80, 57, 13 };

        // public static String toString(int[] a) 把数组转成字符串
        System.out.println("排序前:" + Arrays.toString(arr));

        // public static void sort(int[] a) 对数组进行排序
        Arrays.sort(arr);
        System.out.println("排序后:" + Arrays.toString(arr));

        // [13, 24, 57, 69, 80]
        // public static int binarySearch(int[] a,int key) 二分查找
        System.out.println("binarySearch:" + Arrays.binarySearch(arr, 57));
        System.out.println("binarySearch:" + Arrays.binarySearch(arr, 577));
    }
}

Integer

为了让基本类型的数据进行更多的操作,Java就为每种基本类型提供了对应的包装类类型
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

Integer的构造方法
A:Integer i = new Integer(100);
B:Integer i = new Integer(“100”);

  • 注意:这里的字符串必须是由数字字符组成
public class IntegerDemo {
    public static void main(String[] args) {
        // 方式1
        int i = 100;
        Integer ii = new Integer(i);
        System.out.println("ii:" + ii);

        // 方式2
        String s = "100";
        // NumberFormatException
        // String s = "abc";
        Integer iii = new Integer(s);
        System.out.println("iii:" + iii);
    }
}

int类型和String类型的相互转换
int – String
String.valueOf(number)

String – int
Integer.parseInt(s)

public class IntegerDemo {
    public static void main(String[] args) {
        // int -- String
        int number = 100;
        // 方式1
        String s1 = "" + number;
        System.out.println("s1:" + s1);
        // 方式2
        String s2 = String.valueOf(number);
        System.out.println("s2:" + s2);
        // 方式3
        // int -- Integer -- String
        Integer i = new Integer(number);
        String s3 = i.toString();
        System.out.println("s3:" + s3);
        // 方式4
        // public static String toString(int i)
        String s4 = Integer.toString(number);
        System.out.println("s4:" + s4);
        System.out.println("-----------------");

        // String -- int
        String s = "100";
        // 方式1
        // String -- Integer -- int
        Integer ii = new Integer(s);
        // public int intValue()
        int x = ii.intValue();
        System.out.println("x:" + x);
        // 方式2
        // public static int parseInt(String s)
        int y = Integer.parseInt(s);
        System.out.println("y:" + y);
    }
}

Character

类在对象中包装一个基本类型 char 的值
此外,该类提供了几种方法,以确定字符的类别(小写字母,数字,等等),并将字符从大写转换成小写,反之亦然

构造方法:
Character(char value)

public class CharacterDemo {
    public static void main(String[] args) {
        // 创建对象
        // Character ch = new Character((char) 97);
        Character ch = new Character('a');
        System.out.println("ch:" + ch);
    }
}

// 常用方法

/*
 * public static boolean isUpperCase(char ch):判断给定的字符是否是大写字符 public static
 * boolean isLowerCase(char ch):判断给定的字符是否是小写字符 public static boolean
 * isDigit(char ch):判断给定的字符是否是数字字符 public static char toUpperCase(char
 * ch):把给定的字符转换为大写字符 public static char toLowerCase(char ch):把给定的字符转换为小写字符
 */
public class CharacterDemo {
    public static void main(String[] args) {
        // public static boolean isUpperCase(char ch):判断给定的字符是否是大写字符
        System.out.println("isUpperCase:" + Character.isUpperCase('A'));
        System.out.println("isUpperCase:" + Character.isUpperCase('a'));
        System.out.println("isUpperCase:" + Character.isUpperCase('0'));
        System.out.println("-----------------------------------------");
        // public static boolean isLowerCase(char ch):判断给定的字符是否是小写字符
        System.out.println("isLowerCase:" + Character.isLowerCase('A'));
        System.out.println("isLowerCase:" + Character.isLowerCase('a'));
        System.out.println("isLowerCase:" + Character.isLowerCase('0'));
        System.out.println("-----------------------------------------");
        // public static boolean isDigit(char ch):判断给定的字符是否是数字字符
        System.out.println("isDigit:" + Character.isDigit('A'));
        System.out.println("isDigit:" + Character.isDigit('a'));
        System.out.println("isDigit:" + Character.isDigit('0'));
        System.out.println("-----------------------------------------");
        // public static char toUpperCase(char ch):把给定的字符转换为大写字符
        System.out.println("toUpperCase:" + Character.toUpperCase('A'));
        System.out.println("toUpperCase:" + Character.toUpperCase('a'));
        System.out.println("-----------------------------------------");
        // public static char toLowerCase(char ch):把给定的字符转换为小写字符
        System.out.println("toLowerCase:" + Character.toLowerCase('A'));
        System.out.println("toLowerCase:" + Character.toLowerCase('a'));
    }
}

正则表达式

就是符合一定规则的字符串
常见规则
A:字符
x 字符 x。举例:’a’表示字符a
\ 反斜线字符。
\n 新行(换行)符 (‘\u000A’)
\r 回车符 (‘\u000D’)

B:字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,两头的字母包括在内(范围)
[0-9] 0到9的字符都包括

C:预定义字符类
. 任何字符。我的就是.字符本身,怎么表示呢? .
\d 数字:[0-9]
\w 单词字符:[a-zA-Z_0-9]
在正则表达式里面组成单词的东西必须有这些东西组成

D:边界匹配器
^ 行的开头
$ 行的结尾
\b 单词边界
就是不是单词字符的地方。
举例:hello world?haha;xixi

E:Greedy 数量词
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次

常见功能
A:判断功能
String类的public boolean matches(String regex)

import java.util.Scanner;

public class RegexDemo {
    public static void main(String[] args) {
        // 键盘录入手机号码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的手机号码:");
        String phone = sc.nextLine();

        // 定义手机号码的规则
        String regex = "1[38]\\d{9}";

        // 调用功能,判断即可
        boolean flag = phone.matches(regex);

        // 输出结果
        System.out.println("flag:" + flag);
    }
}

B:分割功能
String类的public String[] split(String regex), 根据给定正则表达式的匹配拆分此字符串。

import java.util.Scanner;

public class RegexDemo {
    public static void main(String[] args) {
        // 定义一个年龄搜索范围
        String ages = "18-24";

        // 定义规则
        String regex = "-";

        // 调用方法
        String[] strArray = ages.split(regex);

        // 遍历
        // for(int x=0; x<strArray.length; x++){
        // System.out.println(strArray[x]);
        // }

        // 如何得到int类型的呢?
        int startAge = Integer.parseInt(strArray[0]);
        int endAge = Integer.parseInt(strArray[1]);

        // 键盘录入年龄
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的年龄:");
        int age = sc.nextInt();

        if (age >= startAge && age <= endAge) {
            System.out.println("你就是我想找的");
        } else {
            System.out.println("不符合我的要求,gun");
        }
    }
}

C:替换功能
String类的public String replaceAll(String regex,String replacement)
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。

public class RegexDemo {
    public static void main(String[] args) {
        // 定义一个字符串
        String s = "helloqq12345worldkh622112345678java";

        // 我要去除所有的数字,用*给替换掉
        // String regex = "\\d+";
        // String regex = "\\d";
        // String ss = "*";

        // 直接把数字干掉
        String regex = "\\d+";
        String ss = "";

        String result = s.replaceAll(regex, ss);
        System.out.println(result);
    }
}

D:获取功能
Pattern和Matcher
Pattern p = Pattern.compile(“a*b”);
Matcher m = p.matcher(“aaaaab”);
find():查找存不存在
group():获取刚才查找过的数据

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {
    public static void main(String[] args) {
        // 模式和匹配器的典型调用顺序
        // 把正则表达式编译成模式对象
        Pattern p = Pattern.compile("a*b");
        // 通过模式对象得到匹配器对象,这个时候需要的是被匹配的字符串
        Matcher m = p.matcher("aaaaab");
        // 调用匹配器对象的功能
        boolean b = m.matches();
        System.out.println(b);

        // 这个是判断功能,但是如果做判断,这样做就有点麻烦了,我们直接用字符串的方法做
        String s = "aaaaab";
        String regex = "a*b";
        boolean bb = s.matches(regex);
        System.out.println(bb);
    }
}

Math

用于数学运算的类

成员变量:
public static final double PI
public static final double E

成员方法:
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):最大值 (min自学)
public static double pow(double a,double b):a的b次幂
public static double random():随机数 [0.0,1.0)
public static int round(float a) 四舍五入(参数为double的自学)
public static double sqrt(double a):正平方根

public class MathDemo {
    public static void main(String[] args) {
        // public static final double PI
        System.out.println("PI:" + Math.PI);
        // public static final double E
        System.out.println("E:" + Math.E);
        System.out.println("--------------");

        // public static int abs(int a):绝对值
        System.out.println("abs:" + Math.abs(10));
        System.out.println("abs:" + Math.abs(-10));
        System.out.println("--------------");

        // public static double ceil(double a):向上取整
        System.out.println("ceil:" + Math.ceil(12.34));
        System.out.println("ceil:" + Math.ceil(12.56));
        System.out.println("--------------");

        // public static double floor(double a):向下取整
        System.out.println("floor:" + Math.floor(12.34));
        System.out.println("floor:" + Math.floor(12.56));
        System.out.println("--------------");

        // public static int max(int a,int b):最大值
        System.out.println("max:" + Math.max(12, 23));
        // 需求:我要获取三个数据中的最大值
        // 方法的嵌套调用
        System.out.println("max:" + Math.max(Math.max(12, 23), 18));
        // 需求:我要获取四个数据中的最大值
        System.out.println("max:"
                + Math.max(Math.max(12, 78), Math.max(34, 56)));
        System.out.println("--------------");

        // public static double pow(double a,double b):a的b次幂
        System.out.println("pow:" + Math.pow(2, 3));
        System.out.println("--------------");

        // public static double random():随机数 [0.0,1.0)
        System.out.println("random:" + Math.random());
        // 获取一个1-100之间的随机数
        System.out.println("random:" + ((int) (Math.random() * 100) + 1));
        System.out.println("--------------");

        // public static int round(float a) 四舍五入(参数为double的自学)
        System.out.println("round:" + Math.round(12.34f));
        System.out.println("round:" + Math.round(12.56f));
        System.out.println("--------------");

        // public static double sqrt(double a):正平方根
        System.out.println("sqrt:" + Math.sqrt(4));
    }
}

Random

用于产生随机数的类
构造方法:
public Random():没有给种子,用的是默认种子,是当前时间的毫秒值
public Random(long seed):给出指定的种子

给定种子后,每次得到的随机数是相同的。

成员方法:
public int nextInt():返回的是int范围内的随机数
public int nextInt(int n):返回的是[0,n)范围的内随机数

import java.util.Random;

public class RandomDemo {
    public static void main(String[] args) {
        // 创建对象
        // Random r = new Random();
        Random r = new Random(1111);

        for (int x = 0; x < 10; x++) {
            // int num = r.nextInt();
            int num = r.nextInt(100) + 1;
            System.out.println(num);
        }
    }
}

System

System类包含一些有用的类字段和方法。它不能被实例化。
方法:
public static void gc():运行垃圾回收器。
public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。
public static long currentTimeMillis():返回以毫秒为单位的当前时间
public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) 从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

import java.util.Arrays;

public class SystemDemo {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int x = 0; x < 100000; x++) {
            System.out.println("hello" + x);
        }
        long end = System.currentTimeMillis();
        System.out.println("共耗时:" + (end - start) + "毫秒");
    }
}

public class SystemDemo {
    public static void main(String[] args) {
        // 定义数组
        int[] arr = { 11, 22, 33, 44, 55 };
        int[] arr2 = { 6, 7, 8, 9, 10 };

        // 请大家看这个代码的意思
        System.arraycopy(arr, 1, arr2, 2, 2);

        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr2));
    }
}

Date/DateFormat

Date是日期类,可以精确到毫秒。

构造方法:
Date():根据当前的默认毫秒值创建日期对象
Date(long date):根据给定的毫秒值创建日期对象

public class DateDemo {
    public static void main(String[] args) {
        // 创建对象
        Date d = new Date();
        System.out.println("d:" + d);

        // 创建对象
        // long time = System.currentTimeMillis();
        long time = 1000 * 60 * 60; // 1小时
        Date d2 = new Date(time);
        System.out.println("d2:" + d2);
    }
}

常用方法
public long getTime():获取时间,以毫秒为单位
public void setTime(long time):设置时间

public class DateDemo {
    public static void main(String[] args) {
        // 创建对象
        Date d = new Date();

        // 获取时间
        long time = d.getTime();
        System.out.println(time);
        // System.out.println(System.currentTimeMillis());

        System.out.println("d:" + d);
        // 设置时间
        d.setTime(1000);
        System.out.println("d:" + d);
    }
}

DateFormat针对日期进行格式化和针对字符串进行解析的类,但是是抽象类,所以使用其子类SimpleDateFormat
SimpleDateFormat的构造方法:
SimpleDateFormat():默认模式
SimpleDateFormat(String pattern):给定的模式
这个模式字符串该如何写呢?
通过查看API,我们就找到了对应的模式
年 y
月 M
日 d
时 H
分 m
秒 s

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DateFormatDemo {
    public static void main(String[] args) throws ParseException {
        // Date -- String
        // 创建日期对象
        Date d = new Date();
        // 创建格式化对象
        // SimpleDateFormat sdf = new SimpleDateFormat();
        // 给定模式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        // public final String format(Date date)
        String s = sdf.format(d);
        System.out.println(s);

        // String -- Date
        String str = "2008-08-08 12:12:12";
        // 在把一个字符串解析为日期的时候,请注意格式必须和给定的字符串格式匹配
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dd = sdf2.parse(str);
        System.out.println(dd);
    }
}

Calendar

它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

public int get(int field):返回给定日历字段的值。日历类中的每个日历字段都是静态的成员变量,并且是int类型。

import java.util.Calendar;

public class CalendarDemo {
    public static void main(String[] args) {
        // 其日历字段已由当前日期和时间初始化:
        Calendar rightNow = Calendar.getInstance(); // 子类对象

        // 获取年
        int year = rightNow.get(Calendar.YEAR);
        // 获取月
        int month = rightNow.get(Calendar.MONTH);
        // 获取日
        int date = rightNow.get(Calendar.DATE);

        System.out.println(year + "年" + (month + 1) + "月" + date + "日");
    }
}

public void add(int field,int amount):根据给定的日历字段和对应的时间,来对当前的日历进行操作。
public final void set(int year,int month,int date):设置当前日历的年月日

public class CalendarDemo {
    public static void main(String[] args) {
        // 获取当前的日历时间
        Calendar c = Calendar.getInstance();

        // 获取年
        int year = c.get(Calendar.YEAR);
        // 获取月
        int month = c.get(Calendar.MONTH);
        // 获取日
        int date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日");

        // 5年后的10天前
        c.add(Calendar.YEAR, 5);
        c.add(Calendar.DATE, -10);
        // 获取年
        year = c.get(Calendar.YEAR);
        // 获取月
        month = c.get(Calendar.MONTH);
        // 获取日
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日");
        System.out.println("--------------");

        c.set(2011, 11, 11);
        // 获取年
        year = c.get(Calendar.YEAR);
        // 获取月
        month = c.get(Calendar.MONTH);
        // 获取日
        date = c.get(Calendar.DATE);
        System.out.println(year + "年" + (month + 1) + "月" + date + "日");
    }
}

总结

本文中主要说了一些常用的对象及方法,在后面的学习中,我们会经常用到,比如String, Date等.所以我们要尽量多练多写敲.,

——- android培训java培训、期待与您交流! ———-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值