Java composite data type

1. Java string

In Java, strings are treated as objects of type String. The String class is located in the java.lang package, which is imported automatically by default.

The String object will not be modified after creation. When we modify a String object, we actually point the original reference to the newly created memory space. And the same String constant Java does not allocate two memory spaces, but points two references to the same space.

public class MyString {
    public static void main(String[] args) {
        String s1="Character string";
        String s2="Character string";
        String s3=s1;
        System.out.println(s1==s2);     // s1 and s2 strings have the same content and point to the same memory space. Output: true
        System.out.println(s1==s3);     // s1 is the same as s3 before modification, output: true
        s1="Modify string";
        System.out.println(s1==s3);     // After modification, s1 points to the new memory space. Unlike s3, the output is false
    }
}

Common methods in String:

If you need to use strings that are often modified, you can save them with StringBuilder class. You can modify strings through append, replace and other methods. After modification, they still point to the same memory address

public class MyString {
    public static void main(String[] args) {
        StringBuilder s4=new StringBuilder("Initial string");
        StringBuilder s5=s4;
        s4.replace(0,10,"Modified string");
        System.out.println(s4);
        System.out.println(s4==s5);     // After modification, it still points to the same block of memory, so the output is: true
    }
}

2. Wrapper classes in Java

The basic data types in Java, such as int and double, do not have the characteristics of objects. In order to have their own methods like other objects, Java provides a wrapper class for each basic data type to operate the basic data types like objects. The basic methods of wrapper classes are used to implement the conversion between types.

Java wrapper classes can be automatically boxed / unboxed, that is, through the = operator to automatically complete the type conversion between basic types and wrapper classes.

                // Defines a variable of type int with a value of 86
		int score1 = 86;       
		// Using int to create Integer wrapper class object, manually boxing
		Integer score2=new Integer(score1);  
                Integer score2=score1;    //Automatic boxing      
		// Convert Integer wrapper class to double type
		double score3=score2.doubleValue();        
		// Convert Integer wrapper class to float type
		float score4=score2.floatValue();        
		// Convert Integer wrapper class to int type, unpack manually
		int score5 =score2.intValue();	
                int score5 = score2        // Automatic dismantling	
		// Convert string to int
		int score6 = Integer.parseInt("666");

Conversion between basic types and Strings:

   

The date class in java.util package can be used to create a time object, and the SimpleDateFormat class in java.text package can be used to convert time into a string of the required format, where "yyyy MM dd HH: mm: ss" is a predefined string, yyyy is four digit year, mm is two digit month, dd is two digit date, HH is hour (using 24-hour system), mm is minute, ss represents seconds, which specifies the target format of the transformation. Finally, the format() method is used to convert the time object Date to the string of the specified format. Conversely, the parse() method can transform the ordinary string into a Date object.

java.util.Calendar class can process time more easily. A Calendar object is obtained by calling getInstance() static method. It represents the current time by default and can be converted to Date object by c.getTime(). More methods for the Calendar object are as follows

The Math class is located in the java.lang package, which contains methods used to perform basic mathematical operations. All methods of the Math class are static methods, so when using the methods in this class, you can directly use the class name. Method name, such as: Math.round();

3. Data collection in Java

Based on various basic data types, Java uses collection classes as containers to store objects with the same properties. By organizing data through collection class, we can quickly insert, delete and query specific data. Moreover, compared with array, the length of Set is flexible and variable, and the search method is not only subscript. The common collection classes in Java are divided into two interfaces, collection and Map. Collection has three sub interfaces: List, Queue, and Set. The common implementation classes of List are array array List, Queue implementation class LinkedList is linked List, and Set implementation class is hash Set. The collection stores data according to one object, and the Map stores data according to the key value pair < key, value >.

The Collection interface specifies the interface methods of the specific implementation classes such as ArrayList and Set. For example, they all use the add() method to add elements, so some method names are common in each class implementation.

ArrayList

ArrayList is an array like container, which stores objects in ArrayList for organization and management. The add() method can insert a single object into the list. addAll() can insert a child list composed of multiple objects into the parent list. When inserting, you can specify the insertion location. You can convert the array of objects into the object list through Arrays.asList() and insert. For example, to insert a Course object into a list courseList:

public void addCourse(){
    Course c1=new Course(1,"data structure");
    Course c2=new Course(2,"operating system");
    Course[] cArr={new Course(3,"Composition principle"),new Course(4,"computer network")};

    courseList.add(c1);                         // Add objects to the array list
    courseList.add(0,c2);                 // Add objects to the specified location
    courseList.addAll(Arrays.asList(cArr));     // Add a sublist to the list, with a number before it indicating the insertion position
    Course tmp=(Course)courseList.get(0);       // Remove objects from list
}

The length of the list can be obtained by the size() method, and the Object at the specified location can be obtained by the get() method. Then, each Object can be traversed by the for loop, and each element can be traversed by the for each method. You can also access each Object through an iterator. It is worth noting that each Object is stored as an Object object Object in the list, so it needs to be cast to the original Object type after fetching, for example, the Object that (Course) is converted to the Course class

    public void showCourse(){
        int listLength=courseList.size();           // Get list length
        for (int i=0;i<listLength;i++) {
            Course c=(Course)courseList.get(i);     // Get the i-th element of the list
            System.out.println(c.name);
        }
    }

    public void iteratorCourse(){
        Iterator it=courseList.iterator();          // Get iterator
        while (it.hasNext()){                       // If there is still another element
            Course c=(Course)it.next();             // Take out the next element
            System.out.println(c.name);
        }
    }

Modify the element of the specified position of the list through the set() method. Remove the specified location or object through the remove() method. Remove elements from all child lists contained in the parent list through removeAll()

    public void modifyCourse(){
        courseList.set(2,new Course(5,"discrete mathematics"));     // Modify the object at position 2
    }

    public void removeCourse(){
        courseList.remove(3);               // Delete objects at 3 locations
        Course c1= (Course) courseList.get(1);
        Course c2=(Course) courseList.get(2);
        courseList.remove(c1);                      // Delete the specified object
        Course[] cArr={c1,c2};
        courseList.removeAll(Arrays.asList(cArr));  // Remove the elements of the cArr contained in the courseList
    }

Determine whether a List contains one or several objects by means of the contains() and containsAll() methods. The implementation principle is to traverse each object in the List and call its equals() method to compare with the target object. If there is any, return true, otherwise return false. Therefore, we can override the equals () method of the Course class, and then call the contains () method to determine whether the List contains the specified Course object. Similarly, the indexOf() method can find the first occurrence of an element in the List by calling equals().

    // Override the equals() method of the Course class
    public boolean equals(Object o) {
        if (this == o) return true;     // If the addresses of two objects are the same, they must be the same
        if (!(o instanceof Course)) return false;
        Course course = (Course) o;
        return id == course.id &&       // Judge that the id and name of two Course objects are the same
                name.equals(course.name);
    }

    // Call contains() in CourseList to see if an object is included.
    public void containCourse(){
        Course nc=new Course(5,"data structure");
        if(courseList.contains(nc)) {                     // Judge whether Course object nc is included in the List
            int index = courseList.indexOf(nc);           // Get the location of the element in the List
            System.out.println("The course is included in the list, location:" + index);
        }
    }

As mentioned before, the objects stored in the collection are all object references. Each time they are saved, the collection ignores the specific types of the objects. Sometimes when they are saved into other types of objects, they will make errors at runtime. Moreover, each time they are taken out, they need to be converted and restored. You can use generics to specify that a collection can only hold objects of a specific type or subtype, so that type checking is performed during compilation, and objects of a specific type can be returned directly when they are retrieved. Note that generics cannot be used for basic data types. For example, list < int > will report errors, but its wrapper class list < integer > should be used.

    // Create a list with element type Course
    public List<Course> courseList=new ArrayList<Course>();

    public void addCourse(){
        Course c=new Course(6,"data structure");
        courseList.add(c);
//        courseList.add("string"); / / try to add an object of non Course type to the list, and an error is reported
        Course c2=courseList.get(0);        // Can be extracted directly as Course type object
        System.out.println(c2.name);
    }

Through the collection. Sort () method, we can sort the List objects. The principle of its implementation is to call the compareTo() method of each element to realize the comparison between objects and then sort them. Therefore, each object must be of a Comparable type, that is, an object that implements the Comparable interface. As shown below, first define the Comparable class Student, then define the Student liststudentlis to add Student objects, and then call the Collections.sort() method to sort the List.

public class Student implements Comparable<Student> {   // Defining Student class to implement compatible interface
    public String name;
    public int id;

    public Student(int id, String name) {
        this.name = name;
        this.id = id;
    }

    @Override
    public int compareTo(Student o) {        // The method of implementing the interface and comparing the students according to the size of id
        if (this.id>o.id){          // Return 1 if greater than o
            return 1;
        }else if (this.id<o.id){    // Less than Return-1
            return -1;
        }else {                     // Equal to return 0
            return 0;
        }
    }
}

public class ListSort {
    public List<Student> studentList=new ArrayList<Student>();    // List of students

    public void sortStudent(){
        Student s1=new Student(1011,"Xiao Ming");
        Student s2=new Student(1005,"Xiao Zhao");
        Student s3=new Student(1021,"Small money");
        Student[] sArr={s1,s2,s3};
        studentList.addAll(Arrays.asList(sArr));
        Collections.sort(studentList);                // Call method to sort the student list
        for (Student s:studentList) {
            System.out.println(s.id+":"+s.name);
        }
    }
}

You can also pass in a custom Comparator object Comparator to compare the two objects when you call the sort() method. At this time, the Student class does not need to implement the Comparable interface

// Custom comparer class to compare two Student objects
public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.id>o2.id){          // Return 1 if greater than o
            return 1;
        }else if (o1.id<o2.id){    // Less than Return-1
            return -1;
        }else {                     // Equal to return 0
            return 0;
        }
    }
}

// The call is modified as follows:
Collections.sort(studentList,new StudentComparator());

HashSet

Hash set is an implementation class of set. Unlike list, the elements in set are unordered and cannot be repeated.

Like List, add() and remove() are used to add and delete elements in Set. Because the Set is unordered, there is no set() or get() method to insert / get elements at the specified location. When traversing elements, it is implemented by for each and iterator, and the result order of each traversal is uncertain.

Note that the contains() method in the HashSet will first call the hashCode() method of the object to compare the hash codes, and then call the equals() method. If both are true, the two objects will be considered the same.

For example, HashSet is used to store the courses selected by students

public class Student {
    public String name;
    public int id;
    public Set<Course> courses;     // Save the course selected by students with set

    public Student(int id, String name) {
        this.name = name;
        this.id = id;
        this.courses=new HashSet<Course>();     //Create Hash set
    }

    public static void main(String[] args){
        Course c=new Course(1,"data structure");
        Student s=new Student(101,"Xiao Ming");     
        s.courses.add(c);               // Adding objects to a set
        for (Course course:s.courses) {         // Ergodic set
            System.out.println(course.name);
        }
    }
}

HashMap

Map stores data in the form of one-to-one key value pair < key, value >. Through the mapping relationship, the key can quickly find value, and the key value cannot be repeated. Map also supports generic map < K, V >. Add key value pairs to the map through put(key,value), and remove(key) remove the key. The key, value, and key value pairs of map can be obtained respectively through keySet(), values(), and entrySet(). The returned key value pair Entry can still define generic types. The put() method is also used to modify the map key value pair. The new key value pair will overwrite the original value. The containsKey(key) method can return whether a key value is included in the map, whether a value is included in the map, and whether it exists by calling the equals() method comparison of the object.

    // Create a hash Map to store student classes
    public Map<Integer,String> studentMap=new HashMap<Integer, String>();

    public void addStudent(){
        Scanner input=new Scanner(System.in);
        System.out.print("Please input students ID: ");
        int studentID=input.nextInt();
        String s=studentMap.get(studentID);        // Get the corresponding value according to the key value
        if (s!=null){                              // If s is not empty, the key already exists
            System.out.println("The student ID Already exist!");
        }else {
            System.out.print("Please enter your name:");
            String name=input.next();
            studentMap.put(studentID,name);     // Add < ID, name > key value pair to Map
        }
    }

    public void showStudent(){
        // Get the key value of Map to define the Entry and its generics
        Set<Map.Entry<Integer,String>> entrySet=studentMap.entrySet();
        for(Map.Entry<Integer,String> entry:entrySet){
            int key= entry.getKey();                    // Get key from Entry
            String name=entry.getValue();               // Get value from Entry
            System.out.println(key+":"+name);
        }
    }

 

99 original articles published, 44 praised, 120000 visitors+
Private letter follow

Tags: Java less network

Posted on Fri, 31 Jan 2020 22:09:00 -0800 by Servyces