zoukankan      html  css  js  c++  java
  • Java学习小知识总结

          通过一学期对JavaSE语言的学习,我总结了几处小知识点。大的框知识点相信很多人都已经学过或者清楚,当然没学过的朋友也可以提前参考一下。

          有一些代码是我从别的老师哪里学习过来的,希望也可以帮到你。

    (刚刚加入到博客园,希望大家会喜欢,我会随时更新随手记和文章,已经加入了博客自定义主题哦,多多观看,不断更新(づ ̄3 ̄)づ╭❤~)

          目录:

    1. compare比较方法
    2. Set集合计算数学公式交并补集

    3. 简易代理设计模式

    4. 简易单例(多例)设计模式

    5. 简易工厂设计模式

    6. 面向接口的向上转型(多态)

    7. 利用Map集合统计单词或者字符的个数

    8. 内省

    9. Java字符串格式化

    10. 自定义时间格式
    11. 集合数组互换
    12. split分割
    13. 随机数

    1.关于compare比较方法

    方法一:以代码的形式讲解,代码如下。这是一个简单的利用面向对象的方法编写的一个题目。

    如果使用 Collections.sort();这个方法进行排序。

    那么需要在 Employee类中实现Comparable<Employee>接口,重写compareTo() 方法。

    然后在Emp类中 addList()方法中使用Collections.sort(climbList);

    class Employee implements Comparable<Employee>{
        private double salary;
        private String name;
    
        public Employee(double salary,String name){
            this.salary = salary;
            this.name = name;
        }
        public double getSalary() {
            return salary;
        }
        public String getName(){
            return name;
        }
    
        public int compareTo(ClimbInfo a) {
        return this.peakName.compareTo(a.peakName);
        } 
    
    }
    
    class Emp{
        private List<Employee> list;
        public Emp(){
        list = new ArrayList<Employee> ();
        }
        
        public boolean addList(double salary,String name){
        list.add(new Employee (salary,name));
    
        Collections.sort(climbList);
        
        return true;
        }
        
    }

     方法二:同样是以上代码,只将class Emp修改一下。

     直径是在addList()方法中使用compareTo()方法进行比较。

    class Emp{
        private List<Employee> list;
        public Emp(){
        list = new ArrayList<Employee> ();
        }
        
        public boolean addList(double salary,String name){
             int insert = list.size();
                    for (int i=0;i<list.size();i++){
                            if(name.compareTo(climbList.get(i).getName())<0){
                                    insert = i;
                                    break;
                            }
                    }
                    climbList.add(insert,new ClimbInfo(name,salary));
        
            return true;
        }
        
    }

     2.Set集合计算数学公式交并补集

    利用面向对象的思想和ArrayList集合,交并补集都有对应的List方法。编写代码如下:

    import java.util.*public class Jihe {
            private String mathematicalAggregati;
            private Set<Jihe> set;
            private Set<Jihe> sett;
            private Set<Jihe> settt;
            public Jihe() {
                set = new HashSet<Jihe>();
                sett = new HashSet<Jihe>();
                settt = new HashSet<Jihe>();
            }
            public String getter(){
                return mathematicalAggregati;
            }
            public Jihe(String mathematicalAggregati) {
                this.mathematicalAggregati = mathematicalAggregati;
            }
            public boolean addAggregati(String all) {
                set.add(new Jihe(all));
                return true;
            }
            public boolean addAggregatii(String all) {
                sett.add(new Jihe(all));
                return true;
            }
            public boolean bing() { //并集
                settt = set;
                return set.addAll(sett);
            }
            public boolean bu() {  //补集
                settt = set;
                return set.removeAll(sett);
            }
            public boolean jiao() { //交集
                settt = set;
                return set.retainAll(sett);
            }
    }
    
    
    
    
    
    
    
    import java.util.*public class M {
    
        public static void main(String[] args) {
            Jihe a = new Jihe();
            a.addAggregati("a");
            a.addAggregati("b");
            a.addAggregati("c");
            a.addAggregati("d");
            a.addAggregatii("q");
            a.addAggregatii("a");
            a.addAggregatii("c");
            System.out.println();
            System.out.println(a.bing());
        }
    
    }

     3.简易代理设计模式

    这是我从51cto学院,李老师的讲授课堂中学到的,受益匪浅。

    这个代理模式的背景故事是:“陶大爷想取回被霸占的1.5亿元,但是他自己抢不回来,通过找一个代理的方式,来帮他要回那1.5亿,代理人有讨债前的准备工作和和讨债后的准备工作”

    我在编写的过程中,编码没有修改为utf-8,导致乱码。以下我配了一张图片,方便理解。具体理解我都写在了图片中。代码,图片如下:

    interface Subject{
        public void get();
    }
    
    class RealSubject implements Subject{ 
        public void get(){
            System.out.println("ÌÕ´óүȡ»ØÁË1.5ÒÚÔª");
        }
    }
    
    class ProxySubject implements Subject{
        private Subject subject; 
        public ProxySubject(Subject subject){
            this.subject = subject;
        }
        public void prepare(){ 
            System.out.println("¡¾×¼±¸µÀ¾ß¡¿Æ¤±Þ...........");
        }
        public void get(){
            this.prepare();
            this.subject.get();
            this.destroy();
        }
        public void destroy(){ 
            System.out.println("¡¾½áÊøÁË¡¿¿ªÊ¼·Öʬ²ØÄä¡£¡£¡£¡£¡£¡£¡£¡£¡£");
        }
    }
    
    public class Main{
        public static void main(String args[]) {
            Subject sub = new ProxySubject(new RealSubject());
            sub.get();
        }
    }

     

     4.简易单例(多例)设计模式

    简单来说,单例设计模式就是私有化的(private)的构造方法,通过getInstance()方法使用。代码如下:

    class SingIeton{
        private static final SingIeton instance = new SingIeton();
        public static SingIeton getInstance() { 
            return instance;
        }
        private SingIeton(){ } 
        public void print() {
            System.out.println("wwwww");
        }
    }
    
    public class Main{
        public static void main(String args[]) {
            SingIeton inst = null; 
            inst = SingIeton.getInstance();
            inst.print();
        }
    }

    5.简易工厂设计模式

    此代码仅适用于理解工程设计模式的原理。通过一个工厂类,可以直接获取到接口的实例,并返回各种类型的对象。

    注:Fruit f = Factory.getlnstance(args[0]),这里的arg[0]的意思就是,当你点击运行的时候,运行结束后在运行框中输入你想输入的内容,例如我写入“apple”,那么就会判断f是不是为空,也就是“apple”是否存在。

    代码如下:

    interface Fruit{
        public void eat();
    }
    class Apple implements Fruit{
        public void eat() {
            System.out.printf("eat apple");
        }
    }
    class Cherry implements Fruit{
        public void eat() {
            System.out.printf("eat cherry");
        }
    }
    class Factory{
        public static Fruit getlnstance(String className) {//直接取得接口实列
            if("apple".equals(className)){
                return new Apple();
            }else if("cherry".equals(className)){
                return new Cherry();
            }else{
                return null;
            }
            
        }
    }
    public class TestDemo{
        public static void main(String args[]) {
            Fruit f = Factory.getlnstance(args[0]);
            if(f!=null){
                f.eat();
            }
        }
    }

    6. 面向接口的向上转型(多态)

    通过多态的方式实现。多态的向上转型也可以在接口中实现。代码如下:

    interface Animal{
        public abstract void cry();
        public abstract String getAnimalName();
    }
    
    class Cat implements Animal{
        public void cry(){
            System.out.println("miao~ miao~ miao~ ......");
        }
        public String getAnimalName(){
            return "Cat";
        }
    }
    
    class Dog implements Animal{
        public void cry(){
            System.out.println("wang wang wang ......");
        }
        public String getAnimalName(){
            return "Dog";
        }
    }
    
    class Simulator{ 
        public void playSound(Animal animal){
            System.out.println(animal.getAnimalName()); 
            animal.cry();    
        }
    }
    
    class Main{
         public static void main(String[] args) {
            Simulator s = new Simulator();
            s.playSound(new Dog());
            s.playSound(new Cat());
        }
    }

     7.利用Map集合统计单词或者字符的个数

    在数组中有这样一个方法。如果存在长篇的英文文章,统计其单词的个数,就需要把他们都分割开来一个一个计算。

    下面代码的意思是用空格分隔 。如果想要以 " .  "分割就需要split(\.)  。同理用" | "分割也是一样。原因就是" . "是转义字符所以 " \. "才表示"    "。还有很多分割方法需要用到正则表达这,在这里我就不多介绍了。

     String[] ss = string.split(" "); 

    利用Map统计单词如下:

    public class Word {
        private Map<String,Integer > map;
        // private static String string ="align border cord did";
        public Word() {
            map = new HashMap<String,Integer>();
        }
        public void putWord(String i,Integer n) {
            map.put(i,n);
        }
        public void get() {
            for(Map.Entry<String,Integer> entry : map.entrySet()) {
                String s = entry.getKey();
                if (!map.containsKey(s)) {
                    map.put(s,0);
                }else {
                    map.put(s,entry.getValue()+1);
                }
                System.out.println("单词"+entry.getKey()+"出现了:"+entry.getValue()+"次");
            }
            
        }
    
    
    class Main{
        public static void main(String[] args) {
            Word word = new Word();
            word.putWord("align",0);
            word.putWord("border",0);
            word.putWord("cord",0);
            word.putWord("did",0);
            word.get();
        }
    }

    如果是长篇文章则需要这样做:其他的不变,只需要改变 public void get() 这个方法即可。代码如下:

    public void put() {
            String[] ss = string.split(" ");  //用空格分隔,对应起来String string里面的空格 。如果想要以 . 分割就需要split(\.);同理|分割也是一样;
            for (int j=0;j<ss.length;j++) {
                String word = ss[j];
                if(!map.containsKey(word)) {
                map.put(word,0);
            }else {
                map.put(word,map.get(word)+1);
            }
            }
            for(Map.Entry<String,Integer> entry : map.entrySet()) {
                System.out.println("单词"+entry.getKey()+"出现了:"+entry.getValue()+"次");
                }
        } 

     8.内省

    这是我从网易云课堂的一位高老师哪里学来的。

    通常我们在一个类中想要使用另一个类的方法,就需要导入对应类的包的路径(import...),还要考虑一些访问权限的问题等。

    那么通过 内省 我们就可以通过获取一个类的字节码(.class),来获取到这个类中的getter和setter方法,并且只能获取这两个方法。

    注:.java文件编译过后就是.class文件,也就是字节码文件。.class文件也可以通过反编译的形式反编译为.Java文件,这两者是可以互逆的。

    代码如下:

    public class User {
        String name;
        String pwd;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPwd() {
            return pwd;
        }
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
        @Override
        public String toString() {
            return "User [name=" + name + ", pwd=" + pwd + "]";
        }
    
    }
    
    
    public class Test {
        public static void main(String[] args) throws Exception {        
    
            User u = User.class.newInstance();
            //获取指定字节码的属性信息
            BeanInfo beanInfo = Introspector.getBeanInfo(User.class,Object.class);
            //获取所有的属性描述器
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                //获取所有属性的名称
                System.out.println(pd.getName());
                //获取get方法
                System.out.println(pd.getReadMethod());
                pd.getWriteMethod().invoke(u, "111");
            }
        }
    }

     Java字符串格式化

    String output = String.format("%s = %d", "joe", 35);

    自定义时间格式

    ①Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
    dateReportTimeBegin = sdf.format(d);

    LocalDateTime rightNow = LocalDateTime.now();

    System.out.println( "当前时刻:"+ rightNow );

    System.out.println( "当前年份:"+ rightNow.getYear() );

    System.out.println( "当前月份:"+ rightNow.getMonth() );

    System.out.println( "当前日份:"+ rightNow.getDayOfMonth() );

    System.out.println( "当前时:"+ rightNow.getHour() );

    System.out.println( "当前分:"+ rightNow.getMinute() );

    System.out.println( "当前秒:"+ rightNow.getSecond() );

    ③ 构造:2019年10月12月12日9时21分32秒
    LocalDateTime beforeDate = LocalDateTime.of(2019, Month.DECEMBER, 12, 9, 21, 32);

    ④ 格式化:LocalDateTime rightNow = LocalDateTime.now();
    String result1 = rightNow.format( DateTimeFormatter.ISO_DATE );
    String result2 = rightNow.format( DateTimeFormatter.BASIC_ISO_DATE );
    String result3 = rightNow.format( DateTimeFormatter.ofPattern("yyyy/MM/dd") );
    // 输出结果:
    格式化后的日期(基本样式一举例):2019-12-13
    格式化后的日期(基本样式二举例):20191213
    格式化后的日期(自定义样式举例):2019/12/13
     

    集合数组互换

    数组变集合:Arrays.asList("hahaha","hehehe","xixixi","lalala")
    
    
    集合变数组:String [] strArr =  list.toArray( new String[]{});
    System.out.println(Arrays.toString(strArr));

    split分割

    以"." 、""、“|”分割字符串,直接用"." 、""、“|”无法分割,因为"." 、""、“|”是特殊字符,需要转义,"\." 、"\"、“\|”。
    
    String goodsStr="100:说的:测试1|10:是的:测试2";
    String[] goodList = goodsStr.split("\|");

    随机数

    ① int r = (int) (Math.random()*9); //生成0到9随机的数字
    
    ② Random random = new Random;
     String num = random.nextInt(9999999) + "";
     StringBuffer sb = new StringBuffer ();
     for(int i = 0; i<7-num.length(); i++){
     sb.append("0");   //保证为7为,不足7位补充0
     }
     num = sb.toString() + num;
     return num;
  • 相关阅读:
    sublime text 4 vim 插件配置
    ssh-keygen 的使用
    distribution transaction solution
    bilibili 大数据 视频下载 you-get
    Deepin 20.2.1 安装 MS SQL 2019 容器版本
    【转】使用Linux下Docker部署MSSQL并加载主机目录下的数据库
    【转】You Can Now Use OneDrive in Linux Natively Thanks to Insync
    dotnet 诊断工具安装命令
    Linux 使用 xrandr 设置屏幕分辨率
    【转】CentOS 7.9 2009 ISO 官方原版镜像下载
  • 原文地址:https://www.cnblogs.com/DavisSamuel/p/12286012.html
Copyright © 2011-2022 走看看