Java学习笔记

1.数组不支持范型 可以通过object来替代范型,在把object型转为范型时需要强转 

package com.lzy.stack;
/*
 * 数组不支持范型 可以通过object来替代范型,在把object型转为范型时需要强转
 * 
 */
public class MyArrayStack<T> {
    
    private Object[] items; //数组
    private int count;  //栈中元素个数
    private int n;    //栈容量
    
    //构造函数 初始化
    public MyArrayStack(int n) {
        //this.items = new T[n];    编译不通过
        this.items = new Object[n]; //使用正确
        this.count = 0;    
        this.n = n;
    }
    
    public boolean push(T item) {
        //栈空间已满 返回false
        if(count == n) return false;
        //栈空间未满 在栈顶加入新元素 返回true
        items[count] = item;
        count ++;    //栈顶加1
        return true;
    }
    
    public T pop() {                  
        if(count == 0) return null;
        T temp = (T)items[count - 1];     //需要强装类型 把Object型转为范型
        count --;
        return temp;
    }
    
    public String toString() {
        String temp = "[";
        for(int i = 0; i < count; i++) {
            temp += items[i];
            temp += ",";
        }
        temp = temp.substring(0, temp.length()-1);
        temp += "]";
        return temp;
    }
}
View Code

 

 2.链表实现栈 头插法 链表头天生是栈顶

package com.lzy.stack;

public class Node {
    public Object element;
    public Node next;
    
    public Node(Object element) {
        this(element,null);
    }
    
    public Node(Object element,Node next) {
        this.element = element;
        this.next = next;
    }
    
    public Object getElement() {
        return element;
    }
    
    
    
}




package com.lzy.stack;

public class MyListStack {
    Node header; //栈顶元素 头插法 链表头天生是栈顶 
    int count;  //栈中元素个数
    int size;   //栈容量
    
    //构造函数 初始化栈
    public MyListStack(int size) {
        header = null;
        count = 0;
        this.size = size;
    }
    
    public boolean push(Object value) {
        //栈满
        if(count == size) return false;
        //栈不满
        header = new Node(value,header);
        count ++;
        return true;
        
    }
    
    public Object pop() {
        //栈空
        if(count == 0) return null;
        //栈不空
        Object object = header.element;
        header = header.next;
        count--;
        return object;
    }
    
    public String toString() {
        String temp = "[";
        while(header != null) {
            temp += header.element;
            temp += ",";
            header = header.next;
        }
        temp = temp.substring(0,temp.length() - 1);
        temp += "]";
        return temp;
    }
}
View Code

3.栈实现括号匹配算法

https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/

package com.lzy.leetcode;

import java.util.HashMap;
import java.util.Stack;

/*
 * 括号匹配
 */
public class Kuohaopipei {
    // Hash table that takes care of the mappings.
      private HashMap<Character, Character> mappings;

      // Initialize hash map with mappings. This simply makes the code easier to read.
      public Kuohaopipei() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
      }

      public boolean isValid(String s) {

        // Initialize a stack to be used in the algorithm.
        Stack<Character> stack = new Stack<Character>();

        for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);

          // If the current character is a closing bracket.
          if (this.mappings.containsKey(c)) {       //containsKey方法有这个key就返回true 
                                                      //containsValue方法 有这个value就返回true

            // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
            char topElement = stack.empty() ? '#' : stack.pop();

            // If the mapping for this bracket doesn't match the stack's top element, return false.
            if (topElement != this.mappings.get(c)) {
              return false;
            }
          } else {
            // If it was an opening bracket, push to the stack.
            stack.push(c);
          }
        }

        // If the stack still contains elements, then it is an invalid expression.
        return stack.isEmpty();
      }    
}
View Code

4.运行时报错 RuntimeException("自定义的报错信息"),不需要导入包就可以直接使用。

5.两个栈实现简单计算器

使用两个栈,一个用来存储操作符(opr),一个用来存储数字(num),在遍历时:

遇到加、减、乘、除、左括号,放进opr里面;
遇到数字,把完整的数字记下来,然后看opr的顶部如果是乘或除的话,就作一次运算,结果还是放进num栈里面;
遇到右括号,因为第二步可以保证乘除已经实现运算完了,所以左右括号区间的opr里面只剩加和减了,把区间内的num按opr是加还是减求和即可,结果依然放进num中;
做完以上遍历后,opr里面应该还会剩一堆加减符号,最后一步还是按类似步骤三的方法求一遍和,就能得到答案了。
有一个小细节,就是可能会遇到开头是“-”的表达式,例如“-1+1”,我们可以事先在num栈里面放一个0以应对这种情况(可以推一下,事先放一个0是不会影响到正常情况的)。

https://leetcode-cn.com/problems/basic-calculator/solution/c-chang-gui-de-liang-ge-zhan-de-jie-fa-by-cyiano/

public class Calculate2{
/*
 * 使用两个栈,一个用来存储操作符(opr),一个用来存储数字(num),在遍历时:

遇到加、减、乘、除、左括号,放进opr里面;
遇到数字,把完整的数字记下来,然后看opr的顶部如果是乘或除的话,就作一次运算,结果还是放进num栈里面;
遇到右括号,因为第二步可以保证乘除已经实现运算完了,所以左右括号区间的opr里面只剩加和减了,把区间内的num按opr是加还是减求和即可,结果依然放进num中;
做完以上遍历后,opr里面应该还会剩一堆加减符号,最后一步还是按类似步骤三的方法求一遍和,就能得到答案了。
有一个小细节,就是可能会遇到开头是“-”的表达式,例如“-1+1”,我们可以事先在num栈里面放一个0以应对这种情况(可以推一下,事先放一个0是不会影响到正常情况的)。

 */
    public int calculate(String s) {
    //两个栈实现简易计算器
        Stack<Character> opr = new Stack<>();
        Stack<Integer> num = new Stack<>();
        num.push(0);
        int index = 0;  //位置索引,逐渐先后,采用编译原理的思路
        while(index < s.length()) {
            if(s.charAt(index) == ' ') { //如果是空格,直接跳过
                index++;
            }else if(s.charAt(index) == '(' || s.charAt(index) == '+' || s.charAt(index) == '-' || s.charAt(index) == '*' || s.charAt(index) == '/') {
                //如果是( + - * / 就入符号栈
                opr.push(s.charAt(index));
                index++;
            }else if (s.charAt(index) == ')' ) { //如果是右括号
                int sum = 0;
                
                while( opr.peek() != '(') {
                      char op = opr.pop();
                     //opr.pop();
                     int n = num.pop();
                    sum += op == '+' ? n : -n; 
                }
                int n = num.pop();
                sum += n;
                opr.pop();
                num.push(sum);
                index++;
            }else { //只剩下数字
                String temp = "";
                while(index < s.length() && s.charAt(index) >= '0' && s.charAt(index) <= '9') {
                    temp += s.charAt(index);
                    index++;
                }
                //把数字入栈 
                num.push(Integer.valueOf(temp));
                //数字入栈后,如果符号栈栈顶元素为* / 则进行计算
                
                if(!opr.isEmpty() && ( opr.peek() == '*' || opr.peek() == '/')) {
                    char op = opr.pop();
                    int sum = 0;
                    int second = num.pop();
                    int first = num.pop();
                    sum = op == '*' ? first * second : first / second;
                    num.push(sum);
                }
                
            }
        }
        //最后符号栈只剩下+ - 把所有数据合起来就行
        int sum = 0;
        while(!opr.isEmpty()) {    
            char op = opr.pop();
            int n = num.pop();
            sum += op == '+' ? n : -n;
        }
        
        return sum + num.pop();
        
    }
    
    public static void main(String[] args) {
        Calculate2 c = new Calculate2();
        int n = c.calculate("(1+(4+5+2)-3)+(6+8)");
        System.out.println(n);
    }
}
View Code

6.

Eclipse 中格式化是多行注释被转成一行注释的解决办法

https://blog.csdn.net/angel_guoo/article/details/78976016

 

7.网络编程步骤模板

package com.lzy.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/*
 * 1.使用DatagramSocket指定端口,创建发送端
 * 2.准备数据 一定转成字节数组
 * 3.封装成DatagramPacket包裹,需要指定目的地
 * 4.发送包裹 send(DatagramPacket p);
 * 5.释放资源
 */
public class UdpClient {
    public static void main(String[] args) throws IOException {
        System.out.println("发送端启动。。。");
        //1.使用DatagramSocket指定端口,创建发送端
        DatagramSocket client = new DatagramSocket(8888);
        //2.准备数据 一定转成字节数组
        String data = "网络编程学习中。。。";
        byte[] datas = data.getBytes(); 
        // 3.封装成DatagramPacket包裹,需要指定目的地
        DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",9999));
        // 4.发送包裹 send(DatagramPacket p);
        client.send(packet);
        // 5.释放资源
        client.close();
    }
}





package com.lzy.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/*
 * 1.使用DatagramSocket指定端口,创建接收端
 * 2.准备容器  封装成DatagramPacket包裹
 * 3.阻赛式接收包裹receive(DatagramPacket packet)
 * 4.分析数据
 * byte[] getData()
 *             getLength()
 * 5.释放资源
 */
public class UdpServer {
    public static void main(String[] args) throws Exception {
        System.out.println("接收端启动。。。");
        //1.使用DatagramSocket指定端口,创建发送端
        DatagramSocket server = new DatagramSocket(9999);
        //2.准备容器  封装成DatagramPacket包裹
        byte[] container = new byte[1024*60];
        // 3.阻赛式接收包裹receive(DatagramPacket packet)
        DatagramPacket packet = new DatagramPacket(container,0,container.length);
        // 4.分析数据
        server.receive(packet);
        byte[] datas = packet.getData();
        System.out.println(new String(datas,0,datas.length));
        // byte[] getData()
        //             getLength()
        // 5.释放资源
        server.close();
    } 
}
View Code
原文地址:https://www.cnblogs.com/jianghuxiao/p/11536922.html