20230504_Java基础

2023年5月4日学习文档

1、JAVA基础

1.0 final和const有什么区别

在Java中,final和const实际上是不同的。Java中没有const关键字,而是使用final来表示常量。final关键字可以用于变量、方法和类上。
在变量上使用final关键字表示该变量只能被赋值一次,即它是一个常量。而const关键字则用于C/C++等编程语言中表示常量。
在方法上使用final关键字表示该方法不能被子类重写,即它是一个不可变方法。在类上使用final关键字表示该类不能被继承,即它是一个不可变类

1.1 实现99乘法表

for(int i=1;i<10;i++){
    for(int j=1;j<10;j++){
            if(i<=j){
                System.out.print(i+"*"+j+"="+(i*j));
            }
            System.out.print("\n");
        }
    }

1.2 面向对象继承、封装、多态

代码示例:

public abstract class Animal {
    private String Name;
    public Animal(String Name){
        this.Name=Name;
    }
    public String getName(){
        return this.Name;
    }
    public abstract  String  bark();
}

public class Cat extends Animal{

    public Cat(String Name){
        super(Name);
    }

    @Override
    public String bark() {
        return "Miao Miao "+getName();
    }
}
public class Dog extends Animal{

    public Dog(String Name){
        super(Name);
    }

    @Override
    public String bark() {
        return "Wang Wang "+getName();
    }
}

public static void main(String[] args){
    Cat cat1=new Cat("mengLu");
    System.out.println(cat1.bark());
    Dog dog1=new Dog("enHeng");
    System.out.println(dog1.bark());
}

1.3 interface工厂模式代码示例

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Circle.draw() method");
    }
}

//然后定义三个实现 Shape 接口的类:
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle.draw() method");
    }
}

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Square.draw() method");
    }
}

//接下来定义一个工厂类 ShapeFactory,用于创建不同的 Shape 对象:
public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if (shapeType == null) {
            return null;
        }
        if (shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        } else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
            return new Rectangle();
        } else if (shapeType.equalsIgnoreCase("SQUARE")) {
            return new Square();
        }
        return null;
    }
}

//使用 ShapeFactory 来获取 Shape 对象
public class FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        shape1.draw();
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        shape2.draw();
        Shape shape3 = shapeFactory.getShape("SQUARE");
        shape3.draw();
    }
}

1.4 interface和抽象类的区别

在Java中,interface和抽象类都是用于实现抽象数据类型的机制,但它们之间存在以下几个主要的区别:
1、抽象类可以有实例变量,而interface中只能定义静态常量。
2、抽象类中可以有非抽象的成员方法,而interface中只能定义抽象方法。
3、一个类只能继承一个抽象类,但可以实现多个interface。
4、抽象类可以提供构造方法,而interface不能。
5、抽象类被认为是对类的一种抽象,而interface被认为是对行为的一种抽象。
总的来说,如果你需要创建一些相关的类,并且这些类有一些通用的属性和行为,那么就可以考虑使用抽象类。
而如果你需要创建一些独立的类,但是它们又需要实现某些共同的行为,那么就应该使用interface。

1.5 java中的集合

java中的集合包括List,Map,Set,其中List包括ArryList和LinkList,Map包括HashMap和TreeMap,Set包括HashSet 和 TreeSet,
其中ArryList底层是数组,LinkList底层是链表,HashMap和HashSet底层是哈希表,TreeMap和TreeSet底层是红黑树。

1.5.1 ArrayList代码示例:

    public static void learningArrayList(){
        ArrayList<String> properties=new ArrayList<>();
        properties.add("Name");
        properties.add("age");
        properties.add("Sex");
        //edit element
        properties.set(2,"Age");
        //delete element
        properties.remove(2);
        //cout the size
        System.out.println(properties.size());
        //loops
        for(String str:properties){
            System.out.println(str);
        }
    }

1.5.2 HashMap代码示例:

    public  static void leaningHashMap(){
        HashMap<Integer,String> countries=new HashMap<>();
        countries.put(0,"China");
        countries.put(1,"America");
        countries.put(2,"New Zealand");
        countries.put(3,"Australia");
        //cout size
        System.out.println(countries.size());
        //get element
        System.out.println(countries.get(0));
        //change ele value
        System.out.println(countries.replace(1,"USA"));
        //delete element
        countries.remove(0);
        System.out.println("---------------\n");
        //loops1
        for(Integer i: countries.keySet()){
            System.out.println(countries.get(i));
        }
        System.out.println("---------------\n");
        //loops 2
        for (String str:countries.values()){
            System.out.println(str);
        }
    }


1.5.2 HashSet代码示例

HashSet 基于 HashMap 来实现的,是一个不允许有重复元素的集合。

    public static void learningHashSet(){
        HashSet<String> webSites=new HashSet<String>();
        webSites.add("google");
        webSites.add("baidu");
        webSites.add("yahoo");
        //delete
        webSites.remove("yahoo");
        //cout size
        System.out.println(webSites.size());
        //loops
        for(String str:webSites){
            System.out.println(str);
        }
    }

1.6 泛型

实现一个泛型栈

import java.util.ArrayList;
import java.util.NoSuchElementException;

public class Stack <E>{
    private ArrayList<E> elements;
    public Stack(){
        elements=new ArrayList<>();
    }
    public void Push(E element){
        elements.add(element);
    }

    public E Pop(){
        if(elements.isEmpty()){
            throw new NoSuchElementException("Stack is empty!");
        }
        return elements.remove(elements.size()-1);
    }
    public boolean isEmpty(){
        return elements.isEmpty();
    }
    public int size(){
        return elements.size();
    }

}

public class Main {
    public static void main(String[] args) {
        Stack<Integer> intStack = new Stack<>();

        intStack.Push(1);
        intStack.Push(2);
        intStack.Push(3);

        System.out.println(intStack.Pop());  // 输出 3

        Stack<String> stringStack = new Stack<>();
        stringStack.Push("say");
        stringStack.Push("hi");
        stringStack.Push("sayHi");
        System.out.println(stringStack.Pop()); //输出 sayHi
    }
}

1.7 Java序列化和反序列化

import java.io.*;

public class Main{
    public static void main(String[] args) {
        // 创建一个Person对象
        Person person = new Person("John", 30);

        // 序列化Person对象到文件person.ser
        try {
            FileOutputStream fos = new FileOutputStream("person.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(person);
            oos.close();
            fos.close();
            System.out.println("Person对象已被序列化到person.ser");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 反序列化person.ser文件到一个新的Person对象
        try {
            FileInputStream fis = new FileInputStream("person.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);
            Person newPerson = (Person) ois.readObject();
            ois.close();
            fis.close();
            System.out.println("person.ser文件已被反序列化到新的Person对象");
            System.out.println("新的Person对象的名字为:" + newPerson.getName());
            System.out.println("新的Person对象的年龄为:" + newPerson.getAge());
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

1.8 Iterator(迭代器)

自定义栈,并实现自定义迭代器,进行迭代

//MyStack class
import java.util.Iterator;

public class MyStack<T> implements Iterable<T> {
    private T[] elements;
    private int size;
    private int capacity;   //容量
    public MyStack(){
        this.capacity=0;
        this.size=0;
        elements=(T[]) new Object[capacity];
    }
    public void push(T ele){
        if(size==capacity){
            expandCapacity();   ///扩展容量
        }
        elements[size++]=ele;
    }
    public T pop(){
        if(size==0){
            throw new IllegalStateException("Stack is empty");
        }
        T ele=elements[--size];
        elements[size]=null;
        return ele;
    }
    public  boolean isEmpty(){
        return size==0;
    }
    private void expandCapacity(){
        if(capacity==0){
            capacity=1;
        }else{
            capacity*=2;//容量*2
        }
        T[] newElements=(T[]) new Object[capacity];
        System.arraycopy(elements, 0, newElements, 0, size);    //这里是复制进去
        elements=newElements;
    }

    public Iterator<T> iterator(){
        return new MyStackIterator();
    }

    public MyStackIterator getIterator() {
        return new MyStackIterator();
    }

   public class  MyStackIterator implements  Iterator<T>{
        public int currentIndex=size-1;
        public  boolean hasNext(){
            return currentIndex>=0;
        }
        public T next(){
            return elements[currentIndex--];
        }
    }
}

//Main.class
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        MyStack<String> stringStack=new MyStack<>();
        stringStack.push("Hello");
        stringStack.push("sayHi");
        stringStack.push("enheng?");
        var iterator = stringStack.getIterator();
        while(iterator.hasNext()){
            String ele = iterator.next();
            System.out.println(ele);
        }
        MyStack<Integer> intStack=new MyStack<>();
        intStack.push(1);
        intStack.push(2);
        intStack.push(3);
        System.out.println("-----------------------\n");
        var intIter=intStack.getIterator();
        while(intIter.hasNext()){
            Integer ele=intIter.next();
            System.out.println(ele);
        }
    }
}

//print:enheng?   sayHi  Hello
//print:3 2 1 

评论

暂无评论