duguqiubai Java Learning Resources

repository·master·Indexed 12 days ago

https://github.com/duguqiubai/java

A comprehensive Java programming curriculum designed for mastery over 27 days. The resources cover core Java concepts including object comparison (equals() vs ==), String internals, Regular Expressions, the Collections Framework (Iterable, Collection, Iterator), GUI event listening mechanisms, and network programming using socket clients.

Tokens
4.3K
Snippets
21
Records
27
Agent score
97%

What's inside duguqiubai-java

  1. Project Package Structure for Login and Registration

    master

    The project follows a standard layered architecture using the following package structure:

    • cn.itcast.pojo: Contains basic user description classes (POJOs).
    • cn.itcast.dao: Defines the interfaces for user operations.
    • cn.itcast.dao.impl: Contains the concrete implementations of the user operation interfaces.
    • cn.itcast.util: Contains utility classes.
    • cn.itcast.view: Contains the UI window classes (Forms).
  2. How String.equals() works in Java

    master

    The equals(Object anObject) method in the String class is used to compare the content of two strings. It follows a specific logic flow to determine equality:

    1. Reference Check: It first checks if both objects point to the same memory address (this == anObject). If they do, it returns true immediately.
    2. Type Check: It verifies if the passed object is an instance of String using instanceof. If not, it returns false.
    3. Length Check: It compares the lengths of the internal character arrays (value.length). If the lengths differ, the strings are not equal.
    4. Character Comparison: If lengths match, it iterates through the internal character arrays (char[] value) and compares each character one by one. If any character mismatch is found, it returns false. If the loop completes, it returns true.
    String s1 = "admin";
    String s2 = "admin";
    System.out.println(s1.equals(s2)); // Returns true
  3. Components of the Event Listening Mechanism

    master

    The event listening mechanism in Java GUI programming consists of four core components:

    1. Event Source (事件源): The object that triggers the event.
    2. Event Object (事件对象): The object that encapsulates the event details (e.g., which key was pressed).
    3. Event Listener Interface (事件监听器接口): An interface that defines the specific methods to be called when an event occurs.
    4. Event Listener Implementation (事件监听器实现): The concrete class that implements the listener interface and defines the actual logic to execute in response to the event.
  4. Understand the relationship between Iterable, Collection, and Iterator

    master

    In the Java Collections Framework, these interfaces form a hierarchy that enables iteration over data structures:

    1. Iterable: The root interface. Any class implementing Iterable must provide an iterator() method that returns an Iterator object.
    2. Collection: Extends Iterable. It represents a group of objects and serves as the base for most collection types.
    3. List: Extends Collection. It represents an ordered collection (sequence) of elements.
    4. Iterator: The object used to traverse the collection. It provides two primary methods: hasNext() to check for remaining elements and next() to retrieve the next element.
  5. Implement Event Listeners using Abstract Classes

    master

    To avoid the requirement of implementing every single method in a large listener interface, you can use an Abstract Adapter Class pattern.

    An abstract class implements the listener interface and provides empty default implementations for all methods. Subclasses can then extend this abstract class and override only the specific methods they are interested in, reducing boilerplate code.

    // 1. Define the interface
    interface Listener {
        void keyTyped();
        void keyPressed();
        void keyReleased();
    }
    
    // 2. Create an Abstract Adapter class
    abstract class ListenerAdapter implements Listener {
        public void keyTyped() {}
        public void keyPressed() {}
        public void keyReleased() {}
    }
    
    // 3. Extend the adapter and override only what is needed
    class MyListener extends ListenerAdapter {
        @Override
        public void keyTyped() {
            System.out.println("Only keyTyped is implemented");
        }
    }
  6. Understand the Login and Registration Class Structure

    master

    The login and registration system is organized into a User class hierarchy and specific UI window classes.

    Class Hierarchy

    • User Class
      • User Description Class: Holds user credentials (username, password).
      • User Operation Class: Contains the logic for login and register operations.
    • Login Window (登录窗体): Provides the UI for logging in. Clicking the login button triggers the login functionality.
    • Registration Window (注册窗体): Provides the UI for registering. Clicking the registration button triggers the registration functionality.
  7. Implement Event Listeners using Interfaces

    master

    The simplest way to implement an event listener is to have a class directly implement the listener interface. This requires the class to provide implementations for all methods defined in the interface.

    // 1. Define the interface
    interface Listener {
        void keyTyped();
        void keyPressed();
        void keyReleased();
    }
    
    // 2. Implement the interface
    class MyListener implements Listener {
        @Override
        public void keyTyped() {
            System.out.println("Key typed event triggered");
        }
    
        @Override
        public void keyPressed() {
            System.out.println("Key pressed event triggered");
        }
    
        @Override
        public void keyReleased() {
            System.out.println("Key released event triggered");
        }
    }
  8. Client protocol message types

    master

    The Client class processes incoming UTF strings from the server. The following protocol markers are used to route messages to the appropriate UI components:

    MarkerPurpose
    @clientThreadUsed to assign a threadID to the client.
    @userlistTriggers c_chatFrame.setDisUsers() to update the online user list.
    @chatTriggers c_chatFrame.setDisMess() to display a new chat message.
    @singleTriggers c_chatFrame.setSingleFrame() for private/single chat updates.
    @serverexitTriggers c_chatFrame.closeClient() when the server shuts down.
  9. Compare objects using equals() vs == in Java

    master

    In Java, there is a fundamental difference between the == operator and the equals() method when comparing objects:

    1. == Operator: Compares the memory addresses (references) of the objects. It returns true only if both variables point to the exact same object in memory.
    2. equals() Method: By default, the Object class implementation of equals() uses == (comparing memory addresses). However, many classes (like String) override this method to compare the actual content or state of the objects.

    Important Note on Type Safety: Calling equals() with an object of a different class (e.g., student.equals(someOtherClassInstance)) will typically return false if the method is implemented correctly, but if the implementation performs an unsafe cast, it may throw a ClassCastException.

    // Assuming Student class overrides equals() to compare name and age
    Student s1 = new Student("张三", 28);
    Student s2 = new Student("张三", 28);
    
    // Returns true if content is the same (if equals is overridden)
    System.out.println(s1.equals(s2)); 
    
    // Returns false if memory addresses are different (even if content is same)
    System.out.println(s1 == s2); 
  10. Initialize and run the Chat Socket Server

    master

    The Server class serves as the main entry point for the chat socket server. To run the server, instantiate Server, associate it with a ServerFrame (the UI component), and call startServer(). The main method provides a standard bootstrap sequence that creates the server, initializes the frame, links them, and makes the frame visible.

    public static void main(String[] args) {
        Server server = new Server();
        ServerFrame serverFrame = new ServerFrame(server);
        server.setServerFrame(serverFrame);
        serverFrame.setVisible(true);
    }
  11. Run the txz_demo application

    master

    The App class serves as the entry point for the txz_demo project. Executing the main method initializes and displays the application's primary user interface by instantiating cn.itcast.txz.ui.MainFrame.

    public class App {
    	public static void main(String[] args) {
    		new MainFrame();
    	}
    }
  12. Use the Client class to connect and chat

    master

    The com.elient.Client class is a thread-based socket client used to connect to a chat server, handle login, and manage real-time messaging.

    To use the client, you typically follow this lifecycle:

    1. Instantiate Client.
    2. Call login(username, hostIp, hostPort) to establish a socket connection.
    3. Call showChatFrame(username) to initialize data streams and start the background listening thread.
    4. Use transMess(mess) to send messages to the server.
    5. Use exitChat() to gracefully exit the chat session.
    Client client = new Client();
    // Attempt to login to the server
    String status = client.login("myUsername", "127.0.0.1", "8888");
    
    if ("true".equals(status)) {
        // Initialize the chat UI and start the background listening thread
        client.showChatFrame("myUsername");
        
        // Send a message
        client.transMess("Hello, world!");
    }