JAVA学习:JAVA中一些常用的方法和使用技巧

目录

一、修改数据结构中的Compare

二、向二维数组中快速填充同一个元素:

三、StringBuilder的常用方法:

四、Math的常用方法:参考链接菜鸟教程

五、字符串

六、容器类


 

 

一、修改数据结构中的Compare

Comparable和Comparator的区别:[https://blog.csdn.net/qq_37768971/article/details/90902611]

应用:比如可以使系统的最小堆变成最大堆,或者自定义优先队列的排序方式

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;

public class Main {

    public static void main(String[] args) {

        // 默认的PriorityQueue, 底层是最小堆
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        for(int i = 0 ; i < 10 ; i ++){
            int num = (int)(Math.random() * 100);
            pq.add(num);
            System.out.println("insert " + num + " in priority queue.");
        }

        while (!pq.isEmpty())
            System.out.print(pq.remove() + " ");

        System.out.println();
        System.out.println();


        // 使用lambda表达式,创建底层是最大堆的PriorityQueue
        PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, (a, b) -> b - a);

        for(int i = 0 ; i < 10 ; i ++){
            int num = (int)(Math.random() * 100);
            pq2.add(num);
            System.out.println("insert " + num + " in priority queue.");
        }

        while (!pq2.isEmpty())
            System.out.print(pq2.remove() + " ");

        System.out.println();
        System.out.println();


        // 使用自定义的Comparator,创建个性化的PriorityQueue
        // 注意:也可以使用lambda表达式。在这里只是为了演示PriorityQueue的不同用法
        // 同理,上一个例子也可以使用自定义的Comparator的方式完成
        class myCmp implements Comparator<Integer>{
            @Override
            public int compare(Integer a, Integer b){
                if(a%10 != b%10)
                    return a%10 - b%10;
                return a - b;
            }
        }
        PriorityQueue<Integer> pq3 = new PriorityQueue<Integer>(10, new myCmp());

        for(int i = 0 ; i < 10 ; i ++){
            int num = (int)(Math.random() * 100);
            pq3.add(num);
            System.out.println("insert " + num + " in priority queue.");
        }

        while (!pq3.isEmpty())
            System.out.print(pq3.remove() + " ");

        System.out.println();
        System.out.println();
    }
}

测试:

insert 54 in priority queue.
insert 1 in priority queue.
insert 35 in priority queue.
insert 54 in priority queue.
insert 85 in priority queue.
insert 43 in priority queue.
insert 42 in priority queue.
insert 53 in priority queue.
insert 89 in priority queue.
insert 91 in priority queue.
1 35 42 43 53 54 54 85 89 91 

insert 85 in priority queue.
insert 18 in priority queue.
insert 13 in priority queue.
insert 87 in priority queue.
insert 2 in priority queue.
insert 69 in priority queue.
insert 51 in priority queue.
insert 71 in priority queue.
insert 21 in priority queue.
insert 18 in priority queue.
87 85 71 69 51 21 18 18 13 2 

insert 21 in priority queue.
insert 92 in priority queue.
insert 46 in priority queue.
insert 19 in priority queue.
insert 35 in priority queue.
insert 86 in priority queue.
insert 32 in priority queue.
insert 39 in priority queue.
insert 60 in priority queue.
insert 55 in priority queue.
60 21 32 92 35 55 46 86 19 39 

二、向二维数组中快速填充同一个元素:

boolean [][]visited=new boolean[10][10];
for (int i=0;i<visited.length;i++){
            Arrays.fill(visited[i],false);
        }

结果:共十行,每一行十个元素,共一百个元素全部都为false。


三、StringBuilder的常用方法:

1.append:添加

StringBuffer sBuffer = new StringBuffer("测试:");
sBuffer.append("www"); 
System.out.println(sBuffer);
结果为: 测试:www

2.reverse(): 将此字符序列用其反转形式取代

StringBuffer stringBuffer=new StringBuffer("abc");
System.out.println(stringBuffer.reverse());
结果为:cba

3.replace(int start, int end, String str):将指定字符串替换start-end之间的元素

StringBuffer stringBuffer=new StringBuffer("abc");
stringBuffer.replace(1,3,"defgh");
System.out.println(stringBuffer);
结果为:adefgh
->可见,start指的是开始的下标,end指的是保留的第一个下标(或者替换掉的第几个数字)2,3的值为:abdefgh   |   3,3,的值为:abcdefgh

4.delete(int start, int end):删除范围内的字符串

StringBuffer stringBuffer=new StringBuffer("abcdefgh");
System.out.println(stringBuffer.delete(0,2));
结果为:cdefgh
->可见,start指的是开始的下标,end指的是保留的第一个下标

5.insert(int offset, String s):在指定下标插入字符串

StringBuffer stringBuffer=new StringBuffer("abcdefgh");
stringBuffer.insert(3,"DSA");
System.out.println(stringBuffer);
结果为:abcDSAdefgh

->可见,offset指的是插入的下标位置 


四、Math的常用方法:参考链接菜鸟教程

 1.abs()
返回参数的绝对值。

2.ceil()  返回大于等于( >= )给定参数的的最小整数,类型为双精度浮点型。

  floor()  返回小于等于(<=)给定参数的最大整数 。

3.round()
它表示四舍五入,算法为 Math.floor(x+0.5),即将原来的数字加上 0.5 后再向下取整,所以,Math.round(11.5) 的结果为12,Math.round(-11.5) 的结果为-11。

4.min()  返回两个参数中的最小值。

  max()  返回两个参数中的最大值。

5.exp()  返回自然数底数e的参数次方。

  log()  返回参数的自然数底数的对数值。

6.pow()  返回第一个参数的第二个参数次方。

  sqrt()  求参数的算术平方根。

7.random() 返回一个随机数。

        Random rand=new Random();
        int i=(int)(Math.random()*2);       //  生成0-100的随机数,包括0不包括100 -- [0,100)
        int j=rand.nextInt(2);      // 这里是一个方法的重载,参数的内容是指定范围
        int k=(int)(Math.random()*2)+2;
//      int j=rand.nextInt(0);            //输入0会报错,因为右边是开区间
        System.out.println("i:"+i+"\nj:"+j+"\nk:"+k); // 分别输出两个随机数

i:0
j:1
k:2 

8.sin/cos/tan/asin/scos/atan


五、字符串

1.字符串转换为数字: 

package com.isea.java;
public class Test {
    public static void main(String[] args) {
        String str = "123";
        Integer num1 = new Integer(str); 
        int num2 = Integer.parseInt(str); 
        Integer num3 = Integer.valueOf(str); 
        System.out.println(num1 + "\t" + num2 + "\t" + num3);//123	123	123
    }

}

2.字符串转字符数组:

String str="string";
char[]c =str.toCharArray();

 字符数组转字符串:

String s=String.valueOf(c)

六、数字:

1.对浮点数保留两位小数:

            sum = 32.768;
            System.out.printf("%.2f",sum);
            System.out.println();
            System.out.println((double)Math.round(sum*100)/100);

结果:

32.77
32.77


七、容器类

1.ArrayList和LinkedList的差别

 

package IMUHERO;

import java.util.*;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<Integer>();
        LinkedList<Integer>linked = new LinkedList<>();

        //ArrayList可以使用add(E e),以及add(int index,E e)
        array.add(1);
        array.add(0,2);
        System.out.println(array);
        //LinkedList可以使用add(E e),以及add(int index,E e),还有addFirst和addLast
        linked.add(1);
        linked.add(0,2);
        linked.addFirst(3);
        linked.addLast(4);
        System.out.println(linked);

        //LinkedList比ArrayList可以多删除头尾
        array.remove(0);
        System.out.println(array);
        linked.remove(0);
        linked.removeLast();
        linked.removeFirst();
        System.out.println(linked);

        //set方法都一样
        array.set(0,100);
        System.out.println(array);
        linked.set(0,100);
        System.out.println(linked);


        //都有get方法,
        array.get(0);
        //LinkedList还有getFirst和getLast
        linked.get(0);
        linked.getFirst();
        linked.getLast();

        for (int i=0;i<10;i++){
            array.add(0,i);
            linked.addFirst(i);
        }
        System.out.println(array);
        System.out.println(linked);

        //计算长度的函数式size
        array.size();
        linked.size();

        //排序需要传入Comparator
        array.sort((a,b)-> a-b);
        System.out.println(array);
        linked.sort((a,b)->a-b);
        System.out.println(linked);

        //可以从另一个容器中导入所有元素
        array.addAll(linked);
        System.out.println(array);
        linked.addAll(array);
        System.out.println(linked);

        //可以克隆自身,返回的是一个对象
        Object o1=array.clone();
        System.out.println("这是克隆array的对象"+o1);
        Object o2=linked.clone();
        System.out.println("这是克隆linked的对象"+o2);

        //可以把复制值给数组
        Object []arr = array.toArray();
        System.out.println(arr);

        //contains方法
        System.out.println(linked.contains(100));
        System.out.println(array.contains(200));

        //使用foreach遍历
        for (int a:array){
            System.out.print(a+" ");
        }
        System.out.println();
        for (int l:linked){
            System.out.print(l+" ");
        }
        System.out.println();
        //使用Iterator遍历
        Iterator a=array.iterator();
        while (a.hasNext()){
            System.out.print(a.next()+" ");
        }


    }
}

result:________________________________________________________________________

[2, 1]
[3, 2, 1, 4]
[1]
[1]
[100]
[100]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 100]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 100]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
这是克隆array的对象[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
这是克隆linked的对象[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100]
[Ljava.lang.Object;@404b9385
true
false
0 1 2 3 4 5 6 7 8 9 100 0 1 2 3 4 5 6 7 8 9 100 
0 1 2 3 4 5 6 7 8 9 100 0 1 2 3 4 5 6 7 8 9 100 0 1 2 3 4 5 6 7 8 9 100 
0 1 2 3 4 5 6 7 8 9 100 0 1 2 3 4 5 6 7 8 9 100

 


排序的常用方法:

public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });

        Collections.sort(list);
    }

七、基本类型:数

1.转16进制:

int countNum = Integer.parseInt(strArr[0], 16);

String result = Integer.toHexString(countNum).toUpperCase() + " " + strOut.trim();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IMUHERO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值