Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use compound data types in Java

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "how to use compound data types in Java". The content is simple and clear. I hope it can help you solve your doubts. Let me lead you to study and learn "how to use compound data types in Java".

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 automatically imported by default.

The String object is not modified after it is created, and 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 = "string"; String S2 = "string"; String S2 = "string"; System.out.println (s1==s2); / / S1, S2 string content is the same, pointing 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); / / S1 points to the new memory space after modification, unlike S3, output: false}}

Methods commonly used in String:

Str.length () / / returns the length of the current string str.indexOf (int ch) / / finds the position where the ch character first appears in the string If no-1str.indexOf (subStr) / / finds the bit where the strsubstring first appears in the string, "str.lastIndexOf (ch) / / finds the position of the last occurrence of the ch character in the string str.lastlndexOf (subStr) finds the position of the last occurrence of the St substring in the string str.substring (beginlndex) / / gets the substring str.substring (beginlndex) from the beginning of the beginlndex position to the end of the string Endlndex) / / get the substring str.trim () from the beginlndex position to the endlndex bit M / / return the string str.equals (obj) with spaces removed before and after / / compare the string with the specified object Return true or falsestr.toLowerCase () / / convert the string to lowercase str.toUpperCase () / / convert the string to uppercase str.charAt (int index) / / get the character str.setCharAt (iPowerc) at the specified position in the string / / set the string str.split (String regex, int limit) / / to split the string into substrings Return string array str.concat (str2) / / concatenate str2 to the end str.getBytes () / convert the string to byte array str.toCharArray () / convert to character array

If you need to use a frequently modified string, you can use the StringBuilder class to save it. You can modify the string through append, replace and other methods, and still point to the same memory address after modification.

Public class MyString {public static void main (String [] args) {StringBuilder s4=new StringBuilder ("initial string"); StringBuilder s5 strings 4; s4.replace (0Ling 10, "modified string"); System.out.println (S4); System.out.println (s4==s5); / / still points to the same block of memory after modification, so the output: true}}

Other types of data can be converted to strings through String.valueOf ().

Char [] arr= {'asides,' dudes,'e'}; String s=String.valueOf (arr); 2. Wrapper classes in Java

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

The Java wrapper class can be boxed / unboxed automatically, that is, the type conversion between the primitive type and the wrapper class is done automatically through the = operator.

/ / define an int type variable with a value of 86 int score1 = 86; / / use int to create an Integer wrapper class object and manually box Integer score2=new Integer (score1); Integer score2=score1; / / automatically boxing / / convert the 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, and unpack int score5 = score2.intValue () manually Int score5 = score2 / / automatically unpack / / convert the string to int int score6 = Integer.parseInt ("666")

Conversion between basic types and strings:

The maximum integer value can be obtained through Integer.MAX_VALUE

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 into a string of the desired format, where "yyyy-MM-dd HH:mm:ss" is a predefined string, yyyy represents a four-digit year, MM represents a two-digit month, dd represents a two-digit date, HH represents an hour (using a 24-hour system), mm represents minutes, and ss represents seconds, thus specifying the target format of the conversion Finally, the format () method is called to convert the time object Date to a string of the specified format, while the parse () method can convert a normal string into a Date object.

The java.util.Calendar class makes it easier to process time by calling the getInstance () static method to get a Calendar object, which by default represents the current time, which can be converted to a Date object through c.getTime (). More methods for Calendar objects are as follows

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

Int minNum=Math.min (2, 3); / / get the minimum value int maxNum=Math.max (2, 3); / / get the maximum value long round=Math.round (3.1415); / / round double floor=Math.floor (3.1415); / / round down double ceil=Math.ceil (3.1415); / / round up double random=Math.random (); / / take the random number 3, Java container between [0Dome 1)

Based on various basic data types, Java uses collection classes as containers to store objects with the same properties. Organizing data through collection classes can quickly insert, delete and query specific data. And compared with the array, the length of the collection is flexible and variable, and there is not only one way to find the subscript. The common collection class in Java is divided into two interfaces: Collection and Map, in which Collection has three sub-interface linked list List, queue Queue and set Set,List. The common implementation class is array sequence ArrayList,Queue implementation class is called linked list, and Set implementation class is hash set. Data is stored as an object in Collection and as key-value pairs in Map.

The Collection interface specifies the interface methods of specific implementation classes such as ArrayList, Set, and so on. 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 that stores objects in ArrayList for easy organization and management. Through the add () method, you can insert a single object into the list, addAll () can insert a child list of multiple objects into the parent list, you can specify the insertion location, you can convert the array into a list through Arrays.asList (), and you can convert the list into an Object [] array through the toArray () method, which you can pass in generic parameters to return an array of a specific type.

It is important to note that the List length converted by Arrays.asList () is fixed and cannot be add (), so an error will be reported; we can add it to a new List list as a sublist, and then insert it.

For example, insert a Course object into the list courseList:

Public void addCourse () {Course c1=new Course (1, "data structure"); Course c2=new Course (2, "operating system"); Course [] cArr= {new Course (3, "principles of composition"), new Course (4, "computer Network")}; courseList.add (C1); / / add object courseList.add (0Maginc2) to the array list / / add the object courseList.addAll (Arrays.asList (cArr)) to the specified location; / / add a sublist to the list, preceded by a number to indicate the insertion position Course tmp= (Course) courseList.get (0); / / take the object Course [] courseArr=courseList.toArray (new Course [courseList.size ()]) from the list; / / convert to a specific type of array}

In particular, int [] and List cannot directly use the asList () / toArray () method to convert each other, but can be added to the List one by one through dirty operations, or traversing int [].

Int [] nums=new int [] {3arr 5je 8}; / / arr to listList numList = Arrays.stream (nums). Boxed (). Collect (Collectors.toList ()); / / list to arrint [] arr = numList.stream (). MapToInt (Integer::valueOf). ToArray ()

The length of the list can be obtained by the size () method, the object at the specified location can be obtained by the get () method, and each object can be iterated through the for loop, or each element can be traversed using the for each method. Access to each object can also be achieved through iterators. It is worth noting that each object is stored in the list as an Object object, so after it is taken out, it needs to be cast to the original object type, such as (Course) to an object of the Course class.

Public void showCourse () {int listLength=courseList.size (); / / get the length of the list for (int item0poliio.id) {/ / return 1 return 1 if greater than o;} else if (this.ido2.id) {/ / return 1 return 1 if greater than o;} else if (o1.id)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report