Getting started with Java - advanced tutorial - 01. Data structure

Keywords: Java Database Attribute JDBC

Original address: http://www.work100.net/training/java-data-structure.html
More tutorials: Beam cloud - free course

data structure

Serial number Chapter in text video
1 Summary -
2 enumeration -
3 vector -
4 Stack -
5 Dictionaries -
6 Hashtable -
7 attribute -

Please refer to the navigation above for reading

1. overview

The Java toolkit provides a powerful data structure. The data structure in Java mainly includes the following interfaces and classes:

  • Enumeration
  • BitSet (BitSet)
  • Vector
  • Stack (Stack)
  • Dictionary (Dictionary)
  • Hashtable
  • Properties

These classes are legacy. In Java 2, a new framework, collection framework, is introduced. We will discuss it later.

2. Enumeration

Although enumeration interface does not belong to data structure itself, it is widely used in other data structures. The enumeration interface defines a way to retrieve consecutive elements from a data structure.

For example, enumeration defines a method called nexterelement, which is used to get the next element of a data structure containing multiple elements.

Example:

Create an EnumTest.java class file and define a Lang enumeration. The code is as follows:

public class EnumTest {

    enum Lang{
        zh_CN,
        en
    }

    public static void main(String[] args) {
        System.out.println("Lang: " + Lang.zh_CN);
        System.out.println("-----------------------");
    }
}

The operation results are as follows:

Lang: zh_CN
-----------------------

Now define the enhanced and language encoded LanguageEnum enumeration. The code is as follows:

public class EnumTest {
    enum LanguageEnum {

        /**
         * English
         */
        LANGUAGE_EN("en"),
        /**
         * Simplified Chinese
         */
        LANGUAGE_ZH_CN("zh_CN"),
        /**
         * Traditional Chinese
         */
        LANGUAGE_ZH_TW("zh_TW");

        private String language;

        LanguageEnum(String language) {
            this.language = language;
        }

        /**
         * Get the specified language type (return Chinese if there is no corresponding language type)
         *
         * @param language Language type
         * @return
         */
        public static String getLanguage(String language) {
            if (isEmpty(language)) {
                return LANGUAGE_ZH_CN.language;
            }
            for (LanguageEnum languageEnum : LanguageEnum.values()) {
                if (languageEnum.language.equalsIgnoreCase(language)) {
                    return languageEnum.language;
                }
            }
            return LANGUAGE_ZH_CN.language;
        }
    }

    public static void main(String[] args) {
        System.out.println("Default language:" + LanguageEnum.getLanguage(""));
        System.out.println("Language:" + LanguageEnum.getLanguage("en"));
        System.out.println("Language:" + LanguageEnum.getLanguage("none"));
        System.out.println("-----------------------");
    }

    public static boolean isEmpty(Object str) {
        return str == null || "".equals(str);
    }
}

The operation results are as follows:

Default language: ABCD cn
 Language: en
 Language: zh cn
-----------------------

Enumeration can also define multiple attributes, as follows:

public class EnumTest {

    enum HttpStatus{
        OK(200, "OK"),
        BAD_REQUEST(400, "BAD REQUEST"),
        UNAUTHORIZED(401, "UNAUTHORIZED"),
        PAYMENT_REQUIRED(402, "PAYMENT REQUIRED"),
        FORBIDDEN(403, "FORBIDDEN"),
        NOT_FOUND(404, "NOT FOUND");

        /**
         * Return code
         */
        private int code;

        /**
         * Return information
         */
        private String message;

        HttpStatus(int code, String message){
            this.code = code;
            this.message = message;
        }

        public int getCode() {
            return code;
        }

        public String getMessage() {
            return message;
        }
    }

    public static void main(String[] args) {
        System.out.println("HttpStatus Code: " + HttpStatus.OK.getCode() + ", Message: " + HttpStatus.OK.getMessage());
        System.out.println("HttpStatus Code: " + HttpStatus.NOT_FOUND.getCode() + ", Message: " + HttpStatus.NOT_FOUND.getMessage());
        System.out.println("-----------------------");
    }
}

The operation results are as follows:

HttpStatus Code: 200, Message: OK
HttpStatus Code: 404, Message: NOT FOUND
-----------------------

3. Vector

Vector class is very similar to traditional array, but the size of vector can change dynamically according to the need.

As with arrays, elements of Vector objects can be accessed through indexes.

The main advantage of using Vector class is that when creating an object, you don't need to specify the size of the object. Its size will change dynamically according to your needs.

Example:

Create a new VictorTest.java file with the following code:

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class VictorTest {
    public static void main(String[] args) {
        Vector<Integer> v1 = new Vector<>();

        v1.addElement(new Integer(1));
        v1.add(1, new Integer(20));
        System.out.println(v1);
        System.out.println(v1.get(0));
        System.out.println(v1.get(1));
        System.out.println("------------------------");

        Vector<String> v2 = new Vector<>();
        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        v2.addAll(list);
        System.out.println(v2);
        System.out.println(v2.firstElement());
        System.out.println(v2.lastElement());
        System.out.println("------------------------");
    }
}

The operation results are as follows:

[1, 20]
1
20
------------------------
[aaa, bbb, ccc]
aaa
ccc
------------------------

4. stack (Stack)

Stack implements a LIFO data structure.

You can think of a stack as a vertically distributed stack of objects. When you add a new element, you put the new element on top of the other elements.

When you take an element from the stack, take an element from the top of the stack. In other words, the last element to stack is taken out first.

Example:

Create a StackTest.java file with the following code:

import java.util.Enumeration;
import java.util.Stack;

public class StackTest {
    public static void main(String[] args) {
        Stack<String> stack1 = new Stack<>();
        stack1.push("aaa");
        stack1.push("bbb");
        stack1.push("ccc");
        System.out.println(stack1);
        //Show all elements in an enumeration (stack)
        Enumeration<String> elements1 = stack1.elements();
        while (elements1.hasMoreElements())
        {
            System.out.print(elements1.nextElement() + " ");
        }
        System.out.println();
        System.out.println(stack1.peek()); // Return the top of stack element without removing
        System.out.println(stack1.search("ccc"));

        System.out.println(stack1.pop()); // Pop up top element
        System.out.println(stack1.search("ccc"));
        System.out.println(stack1.pop());
        System.out.println(stack1.pop());
        System.out.println("---------------------");

        Stack stack2 = new Stack();
        stack2.push(123);
        stack2.push("abc");
        stack2.push(123.05f);
        System.out.println(stack2);
        System.out.println(stack2.pop());
        System.out.println(stack2.pop());
        System.out.println(stack2.pop());
        System.out.println("---------------------");
    }
}

The operation results are as follows:

[aaa, bbb, ccc]
aaa bbb ccc 
ccc
1
ccc
-1
bbb
aaa
---------------------
[123, abc, 123.05]
123.05
abc
123
---------------------

5. Dictionary

A dictionary class is an abstract class that defines the data structure of a key mapped to a value.

When you want to access data through a specific key instead of an integer index, you should use Dictionary.

Because the Dictionary class is an abstract class, it only provides the data structure of key mapping to value, and does not provide a specific implementation.

Example:

Create a new DictionaryTest.java file with the following code:

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

public class DictionaryTest {
    private static Dictionary<String, Object> dic = new Hashtable<String, Object>();

    public static void main(String[] args) {
        dic.put("key1", 123);
        dic.put("key2", "abc");
        dic.put("key3", 123.05f);

        System.out.println(dic);
        System.out.println("size: " + dic.size());
        Enumeration<Object> elements = dic.elements();
        while (elements.hasMoreElements()) {
            System.out.print(elements.nextElement() + " ");
        }
        System.out.println();
        System.out.println("key1=" + dic.get("key1"));
        System.out.println("key2=" + dic.get("key2"));
        System.out.println("key3=" + dic.get("key3"));
        Enumeration<String> keys = dic.keys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement();
            System.out.print(key + "=" + dic.get(key) + ", ");
        }
        System.out.println();
    }
}

The operation results are as follows:

{key3=123.05, key2=abc, key1=123}
size: 3
123.05 abc 123 
key1=123
key2=abc
key3=123.05
key3=123.05, key2=abc, key1=123, 

6. Hashtable

The Hashtable class provides a way to organize data based on user-defined key structures.

For example, in the hash table of the address list, you can store and sort the data according to the zip code as a key, rather than by the person name.

The specific meaning of the hash table key depends entirely on the usage scenario of the hash table and the data it contains.

Example:

Create a new HashtableTest.java file. The code is as follows:

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableTest {
    public static void main(String[] args) {
        Hashtable ht = new Hashtable();
        ht.put("key1", 123);
        ht.put("key2", "abc");
        ht.put("key3", 123.05f);

        System.out.println(ht);
        System.out.println("size: " + ht.size());
        Enumeration<Object> elements = ht.elements();
        while (elements.hasMoreElements()) {
            System.out.print(elements.nextElement() + " ");
        }
        System.out.println();
        System.out.println("key1=" + ht.get("key1"));
        System.out.println("key2=" + ht.get("key2"));
        System.out.println("key3=" + ht.get("key3"));
        Enumeration<String> keys = ht.keys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement();
            System.out.print(key + "=" + ht.get(key) + ", ");
        }
        System.out.println();
    }
}

The operation results are as follows:

{key3=123.05, key2=abc, key1=123}
size: 3
123.05 abc 123 
key1=123
key2=abc
key3=123.05
key3=123.05, key2=abc, key1=123, 

7. Properties

Properties inherit from the Hashtable.Properties class to represent a persistent property set. Each key in the property list and its corresponding value is a string.

The Properties class is used by many Java classes. For example, when you get an environment variable, it is the return value of the System.getProperties() method.

Example:

Create a new PropertiesTest.java file with the following code:

import java.io.*;
import java.util.Date;
import java.util.Properties;

public class PropertiesTest {
    public static void main(String[] args) {
        // Write attribute
        writeProperties();
        System.out.println("---------------------");

        // read attribute
        readProperties();
        System.out.println("---------------------");
    }

    static void writeProperties() {
        Properties properties = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream("config.properties");
            properties.setProperty("url", "jdbc:mysql://localhost:3306/");
            properties.setProperty("username", "root");
            properties.setProperty("password", "root");
            properties.setProperty("database", "users");//Save key value pair to memory
            properties.store(output, "Xiaojun modify" + new Date().toString());
            // Save key value pair to file
            System.out.println("Write completion");
        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static void readProperties() {

        try {
            InputStream in = new BufferedInputStream(new FileInputStream(new File("config.properties")));
            Properties prop = new Properties();

            prop.load(in);
            System.out.println("url: " + prop.getProperty("url"));
            System.out.println("username: " + prop.getProperty("username"));
            System.out.println("password: " + prop.getProperty("password"));
            System.out.println("database: " + prop.getProperty("database"));
            System.out.println("Read completion");
        } catch (FileNotFoundException e) {
            System.out.println("properties Error in writing file path, please check!");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The operation results are as follows:

Write completion
---------------------
url: jdbc:mysql://localhost:3306/
username: root
password: root
database: users
 Read completion
---------------------

Next article: aggregate

If you are interested in the content of the course, you can scan the code to pay attention to our official account or QQ group, and pay attention to our curriculum updates in time.


Posted by jerry_louise on Sat, 07 Mar 2020 16:13:28 -0800