Java composite data type

1. Java String

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

After the String object is created, it will not be modified. When we modify a string object, we actually point the original reference to the newly created memory space. And the same string constant Java will not allocate two memory spaces, but will point two references to the same space.

public class MyString {
    public static void main(String[] args) {
        String s1="字符串";
        String s2="字符串";
        String s3=s1;
        System.out.println(s1==s2);     // s1、s2字符串内容相同,指向相同的内存空间,输出:true
        System.out.println(s1==s3);     // 修改之前s1与s3相同,输出:true
        s1="修改字符串";
        System.out.println(s1==s3);     // 修改之后s1指向新的内存空间,与s3不同,输出:false
    }
}

Common methods in String:

If you need to use frequently modified strings, you can use the StringBuilder class to save, you can modify the string through append, replace and other methods, after the modification still points to the same memory address

public class MyString {
    public static void main(String[] args) {
        StringBuilder s4=new StringBuilder("初始字符串");
        StringBuilder s5=s4;
        s4.replace(0,10,"修改后的字符串");
        System.out.println(s4);
        System.out.println(s4==s5);     // 修改后仍然指向同一块内存,因此输出:true
    }
}

2. Packaging 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, operating the basic data type like an object. The basic methods of the wrapper class are used to convert between types.

The Java packaging class can automatically box / unbox, that is, the type conversion between the basic type and the packaging class is automatically completed by the = operator.

                // 定义int类型变量,值为86
		int score1 = 86;       
		// 使用int创建Integer包装类对象,手动装箱
		Integer score2=new Integer(score1);  
                Integer score2=score1;    //自动装箱      
		// 将Integer包装类转换为double类型
		double score3=score2.doubleValue();        
		// 将Integer包装类转换为float类型
		float score4=score2.floatValue();        
		// 将Integer包装类转换为int类型,手动拆箱
		int score5 =score2.intValue();	
                int score5 = score2        // 自动拆箱	
		// 将字符串转为int
		int score6 = Integer.parseInt("666");

Conversion between basic types and strings:

   

Use the Date class in the java.util package to create a time object, and use the SimpleDateFormat class in the java.text package to convert the time to a string in the desired format, where "yyyy-MM-dd HH: mm: ss" is the pre- Define the string, yyyy means four-digit year, MM means two-month, dd means two-digit day, HH means hour (using 24-hour clock), mm means minute, ss means second, so the target format of conversion is specified, and finally Call the format () method to convert the time object Date to a string in the specified format, otherwise the parse () method can convert the ordinary string to a Date object.

The java.util.Calendar class makes it easier to process time. You can  get a Calendar object by calling the getInstance () static method. By default, it represents the current time. You can use c.getTime () to convert it to a Date object. More methods of the Calendar object are as follows

The Math class is located in the java.lang package and contains methods for performing basic mathematical operations. All methods of the Math class are static methods, so when using methods in this class, you can directly use the class name. The 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 attributes. Organizing data through collection classes can realize the rapid insertion, deletion and query of specific data. And compared with the array, the length of the collection is flexible and variable, and the search method is not only a subscript. The common collection classes in Java are divided into two interfaces, Collection and Map, where Collection has three sub-interfaces linked lists List, queue Queue, and Set. The common implementation class of List is the array sequence ArrayList. The class is a hash set. The data is stored one by one in the Collection, and the data is stored in the Map according to the key-value pair <key, value>.

The Collection interface stipulates the interface methods of 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 the implementation of each class.

ArrayList

ArrayList is a container similar to an array, storing objects in ArrayList for easy organization and management. You can insert a single object into the list through the add () method, addAll () can insert a sublist composed of multiple objects into the parent list, you can specify the insertion position when inserting, you can convert the array of objects into objects through Arrays.asList () The list is then inserted. For example, insert Course object into the list courseList:

public void addCourse(){
    Course c1=new Course(1,"数据结构");
    Course c2=new Course(2,"操作系统");
    Course[] cArr={new Course(3,"组成原理"),new Course(4,"计算机网络")};

    courseList.add(c1);                         // 向数组列表中添加对象
    courseList.add(0,c2);                 // 向指定位置添加对象
    courseList.addAll(Arrays.asList(cArr));     // 向列表中添加子列表,前加数字表示插入位置
    Course tmp=(Course)courseList.get(0);       // 从列表中取出对象
}

You can get the length of the list through the size () method, get the object at the specified position through the get () method, and then traverse each object through the for loop, or you can use the for each method to traverse each element. You can also access each object through an iterator. It is worth noting that each object is stored as an Object object in the list, so after being taken out, it needs to be converted to the original object type by forcible type, such as (Course) is converted to an object of Course class

    public void showCourse(){
        int listLength=courseList.size();           // 获取列表长度
        for (int i=0;i<listLength;i++) {
            Course c=(Course)courseList.get(i);     // 获取列表第i个元素
            System.out.println(c.name);
        }
    }

    public void iteratorCourse(){
        Iterator it=courseList.iterator();          // 获取迭代器
        while (it.hasNext()){                       // 如果仍有下一个元素
            Course c=(Course)it.next();             // 取出下一个元素
            System.out.println(c.name);
        }
    }

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

    public void modifyCourse(){
        courseList.set(2,new Course(5,"离散数学"));     // 修改2位置上的对象
    }

    public void removeCourse(){
        courseList.remove(3);               // 删除3位置上的对象
        Course c1= (Course) courseList.get(1);
        Course c2=(Course) courseList.get(2);
        courseList.remove(c1);                      // 删除指定对象
        Course[] cArr={c1,c2};
        courseList.removeAll(Arrays.asList(cArr));  // 删除courseList中所包含的cArr的元素
    }

Use the contains () and containsAll () methods to determine whether the List contains one or several objects. Its implementation principle is to traverse each object in the List and call its equals () method to compare with the target object. If it exists, 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 the element in the List by calling equals ().

    // 重写Course类的equals()方法
    public boolean equals(Object o) {
        if (this == o) return true;     // 如果两个对象的地址相同,肯定相同
        if (!(o instanceof Course)) return false;
        Course course = (Course) o;
        return id == course.id &&       // 判断两个Course对象的id和name相同
                name.equals(course.name);
    }

    // 在CourseList中调用contains()判读是否包含某个对象
    public void containCourse(){
        Course nc=new Course(5,"数据结构");
        if(courseList.contains(nc)) {                     // 判断List中是否包含Course对象nc
            int index = courseList.indexOf(nc);           // 获取元素在List中的位置
            System.out.println("列表中包含该课程,位置:" + index);
        }
    }

As mentioned earlier, all the objects stored in the collection are references to objects. Each time the collection is stored, the specific type of the object is ignored. Sometimes, other types of objects are stored and errors occur at runtime, and each time they are retrieved, they need to be performed. The type conversion is restored back. You can use generics to specify that a collection can only store objects of a specific type or its subtypes, so that type checking will be performed during compilation, and objects of a specific type can be returned directly when fetched. Note that generics cannot be used for basic data types. For example, List <int> will report an error, and its wrapper class List <Integer> should be used.

    // 创建元素类型为Course的列表
    public List<Course> courseList=new ArrayList<Course>();

    public void addCourse(){
        Course c=new Course(6,"数据结构");
        courseList.add(c);
//        courseList.add("字符串");    // 尝试向列表中添加非Course类型的对象,报错
        Course c2=courseList.get(0);        // 可以直接取出为Course类型对象
        System.out.println(c2.name);
    }

The sorting of List objects can be achieved through the Collections.sort () method of the collection tool class . The principle of its implementation is to call the compareTo () method of each element to compare and sort the objects. Therefore, each object must be a comparable type, that is, an object that must implement the Comparable interface. As shown below, first define the comparable class Student, and then define the student list studentLis. After adding the student object, call the Collections.sort () method to perform the list Sort.

public class Student implements Comparable<Student> {   // 定义Student类实现Comparable接口
    public String name;
    public int id;

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

    @Override
    public int compareTo(Student o) {        // 实现接口的方法,根据id大小对学生进行比较
        if (this.id>o.id){          // 如果大于o返回1
            return 1;
        }else if (this.id<o.id){    // 小于返回-1
            return -1;
        }else {                     // 等于返回0
            return 0;
        }
    }
}

public class ListSort {
    public List<Student> studentList=new ArrayList<Student>();    // 学生列表

    public void sortStudent(){
        Student s1=new Student(1011,"小明");
        Student s2=new Student(1005,"小赵");
        Student s3=new Student(1021,"小钱");
        Student[] sArr={s1,s2,s3};
        studentList.addAll(Arrays.asList(sArr));
        Collections.sort(studentList);                // 调用方法对学生列表进行排序
        for (Student s:studentList) {
            System.out.println(s.id+":"+s.name);
        }
    }
}

You can also pass in a custom comparator object Comparator when calling the sort () method to achieve the comparison of the two objects, then the Student class does not need to implement the Comparable interface

// 自定义比较器类来实现两个Student对象的比较
public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        if (o1.id>o2.id){          // 如果大于o返回1
            return 1;
        }else if (o1.id<o2.id){    // 小于返回-1
            return -1;
        }else {                     // 等于返回0
            return 0;
        }
    }
}

// 调用修改如下:
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, delete and other operations are implemented in Set by add (), remove () and other methods. Because Set is unordered, there is no set (), get () method to insert / get elements at the specified position, and iterate through the elements by for each, 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 code, and then call the equals () method. If both are true, the two objects will be considered the same.

For example, through HashSet to store the course selected by the student

public class Student {
    public String name;
    public int id;
    public Set<Course> courses;     // 用set保存学生所选课程

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

    public static void main(String[] args){
        Course c=new Course(1,"数据结构");
        Student s=new Student(101,"小明");     
        s.courses.add(c);               // 向集中添加对象
        for (Course course:s.courses) {         // 遍历集
            System.out.println(course.name);
        }
    }
}

HashMap

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

    // 创建存储学生类的哈希Map
    public Map<Integer,String> studentMap=new HashMap<Integer, String>();

    public void addStudent(){
        Scanner input=new Scanner(System.in);
        System.out.print("请输入学生ID:");
        int studentID=input.nextInt();
        String s=studentMap.get(studentID);        // 根据key值获取对应的value
        if (s!=null){                              // 如果s不为空说明该key已经存在
            System.out.println("该学生ID已存在!");
        }else {
            System.out.print("请输入姓名:");
            String name=input.next();
            studentMap.put(studentID,name);     // 将<ID,name>键值对添加到Map中
        }
    }

    public void showStudent(){            //通过foreach遍历HashMap
        // 获取Map的键值对Entry并对其泛型进行定义
        Set<Map.Entry<Integer,String>> entrySet=studentMap.entrySet();
        for(Map.Entry<Integer,String> entry:entrySet){
            int key= entry.getKey();                    // 从Entry中获取key
            String name=entry.getValue();               // 从Entry中获取value
            System.out.println(key+":"+name);
        }
    }

    public void showStudent2(){            //通过迭代器遍历HashMap
      Iterator iter = studentMap.entrySet().iterator();
      while (iter.hasNext()) {
          Map.Entry entry = (Map.Entry) iter.next();
          Int key= entry.getKey();
          String name = entry.getValue();
            System.out.println(key+":"+name);
        }
  }

 

Published 124 original articles · Like 65 · Visit 130,000+

Guess you like

Origin blog.csdn.net/theVicTory/article/details/104114219