The introduction

In the last section, we looked at the basics of Gradle 1, which involves strings, arrays, collections, etc.

In this chapter we will learn a series of basic programming knowledge 2, such as: list /map/ array/range and other common data structures, object use, file manipulation, etc

A list of commonly used data structures

(1) Definition of list:

def list = [1.3, -1, -2]
printlin list.class
Copy the code

(2) List sorting:

printlin "Default collation, after sorting:" + list.sort().toListString()
printlin "Specify sort rule, after sort:" + list.sort {a, b ->
       a == b ? 0 :Math.abs(a) < Math.abs(b) ? 1 : -1
}.toListString()
Copy the code

(3) List search:

 // Prints even numbers
printlin list.find { return it % 2= =0 }.toListString()
// Print the base
printlin list.find { return it % 2! =0 }.toListString()
/ / print all
printlin list.toListString()
// Any even number
printlin list.any { return it % 2= =0 }.toListString()
// All cardinals
printlin list.every() { return it % 2! =0 }.toListString()
Copy the code

An array of common data structures

Definition:

def arr = [1.2.3.4] as int[]
int[] arr2 = [1.2.3.4]
Copy the code

A map of common data structures

(1) Definition

 def map = [
   red : '0xffff',
   blue: '0xooo'
]
Copy the code

(2) Index:

printlin map['red']
printlin map.red
Copy the code

(3) Add elements:

map.add = '0xccc'
printlin map.toMapString()
Copy the code

(4) Traversal:

def map2 = [
   1: [age: '16', name: 'davi'].2: [age: '15', name: 'xiaoming'].3: [age: '7', name: 'xiaohong']
]
map2.each { obj ->
 printlin Key is ${obj.key}, value is ${obj.value}"
}
Copy the code

(5) Search:

printlin "Of age 16:" + map2.find { def o -> return o.value.age == 16 }.toMapString()

printlin "Of age greater than 0:" + map2.findAll { def o -> return o.value.age > 0 }.toMapString()

printlin "The number of ages greater than 0 is:" + map2.count { def o -> return o.value.age > 0 }.toMapString()

printlin "Names of students older than 7 are:" + map2.findAll {
     def o -> return o.value.age > 7
 }.collect {
     return it.value.name
}.toMapString()
Copy the code

The scope of commonly used data structures

(1) Definition

def rang = 1.10.
println "First element of scope:" + rang[0]
println "The beginning element of the scope:" + rang.from
println "Last element of scope:" + rang.to
Copy the code

(2) traversal

rang.each {
 println "Loop:" + it
}
Copy the code

(3) Combined with case application:

Start by defining a method

String rangResult(Number number) {
        def result = "Default value"
        
        switch (number) {
            case 0.. <60:
                result = "Fail"
                break
            case 60.. <70:
                result = "Pass"
                break
        }
        
        return result
}
Copy the code

And then the use of methods

println "Result:" + rangResult(65)
Copy the code

Objects such as common data structures

(1) Definition

class Person implements IAction.GroovyObject.Serializable {
    String name

    int age

    def incAge(a) {
        return name + age
    }

    @Override
    void eat(a) {
        println "-- eat --"
    }

    def invokeMethod(String methodName, Object param) {
        return "methodName is : ${methodName}, param is : ${param}"}}Copy the code

(2) Object access

def p = new Person(name: "davi", age: 18)
println "name is : ${p.name}"
println "From obj, name is: ${p.getname ()}"
println "age is : ${p.age}"
Copy the code

(3) Object metaprogramming idea

In Java, if there is no method in the class, there will be directly compiled error;

In Groovy, however, no method compilation is error-free, and only a mechanism is implemented at runtime, which looks like this:

Does a method exist in a class? (1) exists, directly calling (2) does not exist in MetaClass.2.1) exists, directly calling (2.2) does not exist, override class methodMissing method (2.21.) have overridden, direct call (2.22.The invokeMethod method is overwritten.2.22.1.) have overridden, direct call (2.22.2.) no rewrite,throwAbnormal MissingMethodExceptionCopy the code

(4) Dynamically add attributes

Person.metaClass.sex = 'boy'
def p1 = new Person(name: "davi", age: 18)
printlin "Dynamically added property sex is:" + p1.sex
Copy the code

(5) Dynamic addition method

Person.metaClass.sexPrint = { -> printlin "SexPrint sex =" + sex }
def p2 = new Person(name: "davi", age: 18)
p2.sexPrint()
Copy the code

(6) The benefits of dynamically adding attributes/methods:

Normally, we need to add properties or methods to a class in a third-party library. We usually choose inheritance and then add methods.

However, if the class is final, inheritance does not work

This can be done using Groovy’s runtime injection properties/methods, etc

Json operation

(1) Object to JSON string

 def list = [
    new Person(name: 'davi1', age: 18),
    new Person(name: 'davi2', age: 19)
]
println "Object to JSON string:" + JsonOutput.prettyPrint(JsonOutput.toJson(list))
Copy the code

(2) Json to object

def json = ' '' { "name": "davi", "age": "18" } '' '
def j = new JsonSlurper()
println Json to object: name is + j.parseText(json).name
Copy the code

XML operation

(1) XML parsing

def xml = ' '' 
       
       
        George
        
       
        John
        
       
        Reminder
        
       '' '
def xmlP = new XmlSlurper()
def xmlObj = xmlP.parseText(xml)
println "xml to is " + xmlObj.note
Copy the code

(2) XML generation

With the following code:

def sw = new StringWriter()
def xmlBuilder = new MarkupBuilder(sw)
xmlBuilder.langs(type: 'cur') {
  language(flavor: 'static'.'kotlin')
}
println "my xml is : " + sw
Copy the code

Generate XML in the following format:

<langs type = 'cur'>
    <language flavor = 'static'>kotlin</language>
</langs>
Copy the code

File operations

(1) Basic operations

/ / define
String sourcePath = "Your file path"
def file = new File(sourcePath)

// Read line by line
file.eachLine { line ->
  println EachLine mode reads eachLine: + line
}

// Read part of the file
def reader = file.withReader { render ->
   char[] buffer = new char[100]
   render.read(buffer)
   return buffer
}
println "Read part of file:" + reader
Copy the code

(2) File copy

static def copy(String sourcePath, String desc) {
        try {
            def descFile = new File(desc)
            if(! descFile.exists()) { descFile.createNewFile() }// Start copying
            new File(sourcePath).withReader { render ->
                def lines = render.readLines()

                descFile.withWriter { writer ->
                    // write line by line
                    lines.each { line ->
                        writer.append(line + "\r\n")}}}//ok
            return true
        } catch (Exception e) {
            e.printStackTrace()
        }

        //default
        return false
    }
Copy the code

(3) Store objects to files

static def saveObj(Object o, String path) {
        try {
            def descFile = new File(path)
            if(! descFile.exists()) { descFile.createNewFile() } descFile.withObjectOutputStream { out -> out.writeObject(o) }//ok
            return true
        } catch (Exception e) {
            e.printStackTrace()
        }

        //default
        return false
}
Copy the code

(4) Read objects from files

 static def readObj(String path) {
        def obj = null

        try {
            def descFile = new File(path)
            if (descFile == null| |! descFile.exists()) {return null
            }
            descFile.withObjectInputStream { inputStream ->
                obj = inputStream.readObject()
            }
            return obj
        } catch (Exception e) {
            e.printStackTrace()
        }

        //default
        return null
}
Copy the code

At the end

Haha, that’s all for this article (systematic learning and growing together)