Java常用方法

Java

整理Java中常用的方法


一、常用类集的方法

1.java.util.Objects

public class Demo2 {
    public static void main(String[] args) {
        /**
         * java.util.Objects
         */
         
        //equals(Object a,Object b)
        Person p1 = null;
        Person p2 = new Person();
         System.out.println(Objects.equals(p1,p2));//false

        //isNull​(Object obj)
        System.out.println(Objects.isNull(p1));   //true

        //requireNonNull​(T obj)
        System.out.println(Objects.requireNonNull(p1)); //抛出NullPointerException

    }
}

2.java.util.BigDecimal

public class Demo03 {
    /**
     * BigDecimal 用于提高运算精度
     */
    public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal("10.5");
        BigDecimal b2 = new BigDecimal("10.5");

        //加法
        BigDecimal b3 = b1.add(b2);
        System.out.println(b3);//21.0
        //加法-转化类型(整形)
        int b4 = b3.intValue();
        System.out.println(b4);//21

        //减法
        BigDecimal b5 = b1.subtract(b2);
        System.out.println(b5);//0.0

        //乘法
        BigDecimal b6 = b1.multiply(b2);
        System.out.println(b6);//110.25

        //除法
        BigDecimal b7 = b1.divide(b2);
        System.out.println(b7);//1
    }
}

3.java.util.Calender


/**
 *  Calendar类用于在日期和时间字段之间进行转换
 */
public class Demo05 {
    public static void main(String[] args) {
        //Calendar是抽象类,用getInstance来创建
        Calendar c1 = Calendar.getInstance();
        //set 可以将当前对象设为相应的日历
        c1.set(Calendar.YEAR,2022);
        //add方法int field, int amount),根据日历的规则,将指定的时间量添加或减去给定的日历字段。
        c1.add(Calendar.YEAR,2);
        //月份是0-11
        //周是星期日为第一天
        //get方法
        int year = c1.get(Calendar.YEAR);
        System.out.println(year);
        int day = c1.get(Calendar.DAY_OF_YEAR);
        System.out.println(day);
        //getTime:获取日历时间 表示的Date对象
        Date d = c1.getTime();
        System.out.println(d);
        //getActualMaxmum 获取某字段的最大值,如下:获取当前一年中最多有多少天
        int m=c1.getActualMaximum(Calendar.DAY_OF_YEAR);
        System.out.println(m);//365

    }
}

4.java.util.Arraylist

java.util.Arraylist是大小可变的数组的实现,存储在内的数据称为元素。此类提供了一些方法来操作
内部存储的元素。Arraylist中可以不断添加元素,其大小自动增长。

创建的基本格式:Arraylist<String>  list = new Arraylist<String>();
import java.util.ArrayList;

public class Arraylist {
    public static void main(String[] args) {
        //创建集合对象
        ArrayList<String> list = new ArrayList<>();

        //public boolean add(E e)添加元素
        list.add("love");
        list.add("is");
        list.add("gone");

        System.out.println(list);

        System.out.println("------");

       // public E get(int index):返回此集合中指定位置上的元素,获取返回值(返回指定索引处的元素)
        System.out.println("get:"+list.get(0));
        System.out.println("get:"+list.get(1));
        System.out.println("get:"+list.get(2));

        System.out.println("-------");

        //public int size():返回集合中的元素个数
        System.out.println("size:"+list.size());

        System.out.println("--------");
        
        //public E remove(int index):删除指定索引处的元素,返回被删除的元素
        System.out.println("remove:"+list.remove(0));

        System.out.println("----------");

        //遍历
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
}
Arraylist对象不能直接存储基本类型,只能存储引用类型。比如类似于<int>是错的,那么可以用存储基本
数据类型对应的包装类型进行存储。基本类型的转换如下:
基本类型基本类型的包装类
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean
举个例子
import java.util.ArrayList;

public class Demo10 {
    public static void main(String[] args) {
        ArrayList<Integer> list  = new ArrayList<Integer>();

        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        System.out.println(list);
    }
}

在这里插入图片描述
Arraylist练习

数值添加到集合

import java.util.Random;

/** 
 * 生成6个1~33之间的随机整数,添加到集合,并遍历
 */
public class Demo10 {
    public static void main(String[] args) {
        //创建Arraylist对象
        ArrayList<Integer> list  = new ArrayList<Integer>();

        //创建Random对象
        Random random = new Random();

        //添加随机数到集合
        for (int i=0;i<6;i++){
            int r = random.nextInt(33)+1;
            list.add(r);
        }
        
        //遍历输出
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }
}

对象添加到集合

import java.util.ArrayList;

public class Demo11<s1> {
    public static void main(String[] args) {
        //创建集合对象
        ArrayList<Student> list = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("小学生",10);
        Student s2 = new Student("中学生",16);
        Student s3 = new Student("大学生",20);

        //把学生对象作为元素添加到集合中
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //遍历集合
        for (int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
    }

}
class Student{
    private String name;
    private int age;

    public Student(){}

    public Student(String name, int age) {
        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
                "name='" + name + '\'' +
                ", age=" + age ;
    }
}

获取集合方法

import java.util.ArrayList;
import java.util.Random;

/**
 * 定义获取所有偶元素集合的方法(ArrayList类型作为返回值)
 */
public class Demo13 {

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

        //创建ArrayList对象
        ArrayList<Integer> list = new ArrayList<Integer>();

        //添加随机数到集合
        for (int i = 0;i<20;i++)
        {
            int r = random.nextInt(1000)+1;
            list.add(r);
        }

        //调用方法
        ArrayList<Integer> arrayList = getArrayList(list);
        System.out.println(arrayList);
    }

    public static ArrayList<Integer> getArrayList(ArrayList<Integer> list)
    {
        //创建小集合来存储偶数
        ArrayList<Integer> smallList = new ArrayList<>();
        //遍历list
        for (int i = 0;i<list.size();i++)
        {
            //获取元素
            Integer num = list.get(i);
            //判断是否为偶数,如果是放到小集合中
            if (num % 2 ==0)
            {
                smallList.add(num);
            }
        }
        return smallList;
    }

}

5.java.util.Random

此类的实例用于生成随机数
常用方法:public int nextInt(int n):返回一个伪随机数,范围在0~n之间,包括0但不包括。

案例

import java.util.Random;

public class Demo14 {
    public static void main(String[] args) {
        int n=10;
        //创建Random对象
        Random random = new Random();

        //获取随机数
        int number = random.nextInt(n);

        //输出
        System.out.println(number);
    }
}

猜数字游戏

import java.util.Random;
import java.util.Scanner;

public class Demo15 {
    /**
     * 猜数字游戏
     */
    public static void main(String[] args) {
        //产生一个100以内的随机数
        Random random = new Random();

        int n =random.nextInt(100)+1;

        //用一个死循环,来进行猜数
        while(true)
        {
            //键盘输入一个数
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入你要猜的数(1~100)");
            int number = scanner.nextInt();

            //比较
            if (number>n)
            {
                System.out.println("你猜的数据:"+number+"大了");
            }
            else if (number<n)
            {
                System.out.println("你猜的数据:"+number+"小了");
            }
            else
            {
                System.out.println("恭喜你猜对了");
                break;
            }
        }
    }

}

6.java.util.String

String类代表字符串,包含用于检查各种字符串的方法,比如比较字符串、搜索字符串、提取字符串等

1.判断功能的方法:

public boolean equals(Object o):将此字符串与指定对象进行比较
public boolean equalsIgnoreCase(String anotherString):将此字符串与指定对象进行比较,忽略大小写

举例

public class Demo16 {
    public static void main(String[] args) {
        //创建字符串
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "Hello";

        //public boolean equals(Object o):比较字符串内容是否相同
        System.out.println(s1.equals(s2));  //  true
        System.out.println(s1.equals(s3));  //  false

        //public boolean equalsIgnoreCase(String anotherString):比较字符串内容是否相同,忽略大小写
        System.out.println(s1.equalsIgnoreCase(s2));    // true
        System.out.println(s1.equalsIgnoreCase(s3));    // true
    }
}

2.获取功能的方法

public int length():返回此字符串的长度
public String concat(String str):将指定的字符串连接到该字符串的末尾
public char charAt(int index):返回指定索引处的char值
public int indexOf(string str):返回指定字符串第一次出现在该字符串内的索引
public String subString(int beginIndex):返回一个子字符串,从beginIndex开始截取字符串到字符串结尾
public String subString(int beginIndex,int endIndex):返回一个子字符串,从beginIndex到endIndex,不包括endIndex
public class Demo17 {
    public static void main(String[] args) {
        //创建字符串
        String s ="Hello";

        //public int length():返回此字符串的长度
        System.out.println(s.length()); //5

        //public String concat(String str):将指定的字符串连接到该字符串的末尾
        String s1 = "world";
        String s2 =s.concat(s1);
        System.out.println(s2);    //Helloworld

        //public char charAt(int index):返回指定索引处的字符
        System.out.println(s.charAt(0));    //H
        System.out.println(s.charAt(1));    //e

        //public int indexOf(string str):获取str在字符串对象中第一次出现的索引,没有返回-1;
        System.out.println(s.indexOf('H')); //0
        System.out.println(s.indexOf('e')); //1

        //public String subString(int beginIndex):返回一个子字符串,从beginIndex开始截取字符串到字符串结尾
        System.out.println(s.substring(1)); //ello

        //public String subString(int beginIndex,int endIndex):返回一个子字符串,从beginIndex到endIndex,不包括endIndex
        System.out.println(s.substring(0,2));   //He


    }
}

3.转换功能的方法

public char[] toCharArray():将此字符串转换为新的字符串数组
public byte[] getBytes():使用平台的默认字符集将该String编码转换为新的字节数组
public String replace(CharSequence target,CharSequence replacement):将与target匹配的字符串使用
replacement字符串代替
public class Demo18 {
    public static void main(String[] args) {
        //创建字符串
        String s = "abcde";


        //char[] toCharArray():把字符串转换成字符数组
        char[]  chars = s.toCharArray();
        for (int i=0;i<chars.length;i++)
        {
            System.out.println(chars[i]);
        }

        //byte[] getBytes():把字符串转换为字节数组
        byte[] bytes = s.getBytes();
        for (int i=0;i<bytes.length;i++)
        {
            System.out.println(bytes[i]);
        }
        //替换
        String string = "hello";
        String replace = string.replace('h','H');
        System.out.println(replace);
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值