在项目中学到的各种知识

项目中学到的杂知识


1.使用collection 进行排序

     Collections.sort(tmpList, new Comparator<ScanResult>() {
            @Override
            public int compare(ScanResult scanResult, ScanResult t1) {
                return t1.level-scanResult.level ;
            }
        });

2.将枚举类型直接转换为数组

   EnumType[] enumArrays = EnumClass.values(); //便可将枚举类型转换为数组类型

3.byte[ ] 类型数组与String类型的转换

    byte [] b = "hello".getBytes();
    String str = new String(b,"utf-8");
    String str3 = new String(b);
    String str2 = new String(b,0,b.length);
    /**new String(bytes, offset, length)
    bytes为要解译的字符串,
    offset为要解译的第一个索引,比如从0开始就是从字符串bytes的第一个字符开始;
    length为要解译的字符串bytes的长度*/

4.将有着不同参数类型的相同方法进行合并
解释:就是两个方法,参数不同,但其中有部分代码相似,就可以将两个方法进行合并。
举例:

public class Test {
    public static void main(String[] args) {
    Test t = new Test();
    int age = 21;
    String home = "中國";
    String name = "一方";
    String introduce1 = t.user(age, name);
    String introduce2 = t.user(name, home);
    System.out.println(introduce1);
    System.out.println(introduce2);
    }
    private String  user(int age,String name) {
        String local = "黑龍江";
        return  user(name,age,local);
    }
    private String  user(String name,String location) {
        int age = 18;
        return user(name,age,location);
    }
    private String  user(String name,int age,String location) {
        String introduce="自我介绍:"+"\n"+" 我的名字:"+name+" 年龄:"+age+" 來自:"+location;
        return introduce;
    }
}
/**解释一下:就是当项目中遇到,我需要用到类似的方法,但我传入的参数可能不同,最终想要的结果是相同的,
   则需要将两个方法进行合并,将公共部分进行抽离提取,免去不必要的重复代码。*/

猜你喜欢

转载自blog.csdn.net/weixin_37716758/article/details/81393765