What are the Java data structures and classes? A lot of Java beginners may not remember or remember so much, today, Xi ' an Java Training series for everyone to tidy up the Java data structure and class knowledge, I hope to help you.
First, the Vector class
A vector is similar to an array, but has the following two advantages over the use of the array.
1, the use of the time without declaring the upper limit, as the element increases, the length of the vector will automatically
Increase.
2, Vector provides an additional way to add, delete elements, more efficient than array operation.
The vector class has three constructors, as follows:
public Vector ();
This method creates an empty vector.
Public Vector (int initialcapacity);
This method creates a vector with an initial length of initialcapacity.
Public Vector (int intialcapacity,int capacityincrement);
This method creates a vector with an initial length of initialcapacity and increments the capacityincrement element when the vector needs to grow.
(1) The methods for adding and deleting objects in the vector class are as follows:
public void Add (int index,object elemtent)
Adds an object element at the index position.
Public boolean Add (Object o)
Adds an object o at the end of the vector.
Public Object Remove (int index)
Delete the object at the index position, followed by the next object.
(2) The methods for accessing and modifying objects in the vector class are as follows:
Public Object get (int index)
Returns the index position object.
Public Object Set (int index,object element)
The object that modifies the index position is element.
(3) Other methods:
Public String toString ()
Converts an element into a string.
public int size ()
Returns the length of the object.
Example 1: Manipulating a Vector object to add, insert, modify, and delete elements. The program output results in 1. The source program code is as follows:
program file name is Usevector.java
Import java.util.vector;//the Vector class that introduced the JDK
public class Usevector
{
public static void Main (string[] args)
{
Vector vscore=new vector ();
Vscore.add ("86");//Add Element
Vscore.add ("98");//Add Element
Vscore.add (1, "99");//Insert Element
Output results
for (int i=0;i<vscore.size (); i++) </vscore.size (); i++)
{
System.out.print (Vscore.get (i) + "");
}
Vscore.set (1, "77");//Modify the second element
Vscore.remove (0);//Delete First element
System.out.println ("\ n modified and deleted after");
for (int i=0;i<vscore.size (); i++) </vscore.size (); i++)
{
System.out.print (Vscore.get (i) + "");
}
SYSTEM.OUT.PRINTLN (: \ n converted to string output \ n "+vscore.tostring ());
}
};
650) this.width=650; "src=" Http://p2.pstatp.com/large/1923000714d0408878c8 "border=" 0 "width=" 640 "/>
Figure 1: Output of manipulating vector objects
Second, Hashtable class
The Hashtable class stores the name-value pairs of an object. Associates the name of an object with its value, stores it, and extracts its value according to the object name. In Hashtable, a key name can only correspond to a key value, but a key value may correspond to multiple key names, and the key name must be unique. Constructors and common methods are as follows:
Public Hashtable ()
Build a hash table.
Public Hashtable (int initialcapacity)
Build a hash table with a length of initialcapacity.
public int size ()
Returns the number of names of the hash table.
public object Remove (object key)
Deletes the key name and its corresponding value value in the hash list.
public object put (object Key,object value)
The object name key and the object value values are stored in the hash table.
public object get (object key)
Returns the value corresponding to the hash list key name.
Public String toString ()
Converted to a string.
Example 2: Operation Hashtable object, add, modify, delete and so on, output result 2 shows. The source program code is as follows:
program file name is Usehashtable.java
Import java.util.hashtable;
public class Usehashtable
{
public static void Main (string[] args)
{
Hashtable hscore=new Hashtable ();
Hscore.put ("Zhang Yi", "86");
Hscore.put ("Li er", "98");
Hscore.put ("Hai Fei", "99");
SYSTEM.OUT.PRINTLN ("Output after converting to a string
Out: "+hscore.tostring ());
Hscore.put ("Li er", "77");
Hscore.remove ("Zhang Yi");
SYSTEM.OUT.PRINTLN ("After modification and deletion");
SYSTEM.OUT.PRINTLN ("Output after conversion to string:" +hscore.tostring ());
}
}
Figure 2: Operation Hashtable object output results
Third, enumeration interface
The object that implements the enumeration interface generates a series of elements that read the next element sequentially through the Nextelement () method. Only the following two methods are available:
public boolean hasmoreelements ()
Test if there are elements
Public Object nextelement ()
Returns the next element of the enumeration.
The enumeration interface and its methods are usually used with vectors and Hashtable to enumerate the keys in the vector and the key names in the Hashtable, for example:
For (enumeration e=v.elements (); e.hasmoreelements ();)
System.out.println (E.nextelement ());
Example 3: Use the enumeration interface to enumerate the object in the vector and the key names in the Hashtable object, and to output, as shown in result 3. The source program code is as follows:
program file name Useenumeration.java
Import java.util.*;
public class Useenumeration
{
public static void Main (string[] args)
{
Vector vscore=new vector ();
Vscore.add ("86");
Vscore.add ("98");
Vscore.add (1, "99");
System.out.println ("Vector:" +vscore.tostring ());
For (enumeration e=vscore.elements (); e.hasmoreelements ();)
System.out.println (E.nextelement ());
Hashtable hscore=new Hashtable ();
Hscore.put ("Zhang Yi", "86");
Hscore.put ("Li er", "98");
Hscore.put ("Hai Fei", "99");
System.out.println ("Hashtable:" +hscore.tostring ());
For (enumeration E=hscore.keys (); e.hasmoreelements ();)
{
String str= (String) e.nextelement ();
System.out.print (str+ ":");
SYSTEM.OUT.PRINTLN (Hscore.get (str));
}
}
}
650) this.width=650; "src=" http://p2.pstatp.com/large/1923000714d1c5eee114 "border=" 0 "width=" 640 "/>
Figure 3: Enumerating output using the enumeration interface
Iv. Date Class
The date class is used to specify dates and times, and its constructors and common methods are as follows:
Public Date ()
Constructs a date-time object from the current time.
Public String toString ()
Converted to a string.
Public long GetTime ()
Returns the number of milliseconds since the beginning of the century, which can be used for time calculations.
Example 4: The time taken to test the execution cycle (in order of milliseconds), as shown in the time situation 4. The source program code is as follows:
program file name is Usedate.java
Import Java.util.Date;
public class Usedate
{
public static void Main (string[] args)
{
Date Dold=new date ();
Long Lold=dold.gettime ();
SYSTEM.OUT.PRINTLN ("The system time before the cycle is:" +dold.tostring ());
int sum=0
for (int i=0;i<100;i++)
{
Sum +=i;
}
Date Dnew=new date ();
Long Lnew=dnew.gettime ();
SYSTEM.OUT.PRINTLN ("The system time after the loop is:" +dnew.tostring ());
System.out.println ("The number of milliseconds spent in the loop is:" + (Lnew-lold));
}
}
650) this.width=650; "src=" http://p2.pstatp.com/large/19ee000111fe2ffece0f "border=" 0 "width=" 640 "/>
Figure 4: Cycle Time Test
V. String class
The string class is used to manipulate non-numeric strings, which provide seven types of method operations, such as string creation, string length, string comparison, string retrieval, string interception, string manipulation, and data type conversions.
1. String creation
Public String ()
Constructs an empty string.
Public String (char[] value)
Uses the character in the string array value to construct a string.
public string (string original)
Use a copy of the original string original to construct a new string.
2. String length
public int Length ()
Returns the length of the string.
3. String comparison
public boolean equals (Object anobject)
Compares whether the string is the same as the string represented by AnObject (case-sensitive).
public boolean equalsignorecase (String anotherstring)
Compares whether the string is the same as anotherstring (case insensitive).
4. String retrieval
public int IndexOF (String str)
Returns the location where Str first appears in a string.
public int indexOf (String str,int fromIndex)
Returns the position where the string str appears starting from Fromindex.
5. String interception
Public String substring (int beginindex,int endIndex)
Returns a string between Benginindex and Endindex.
6. String arithmetic
The operator is "+", which represents the join operation. The following line statement outputs the concatenated string
System.out.println ("Hashtable:" +hscore.tostring ());
Example 5: The action string, as shown in output 5. The source program code is as follows:
program file name is Teststring.java
public class TestString
{
public static void Main (string[] args)
{
String Str=new string ("The substring begins at the specified beginindex.");
String Str1=new string ("string");
String Str2=new string ();
int size=str.length ();//String length
int Flag=str.indexof ("substring");
Str2=str.substring (flag,flag+9);//substring
System.out.println ("string" +str+ "\ n total length is:" +size);
if (Str1.equals (STR2))//Determine equality
System.out.println ("truncated string:" +str1)
Else
System.out.println ("truncated string:" +STR2);
}
}
650) this.width=650; "src=" HTTP://P2.PSTATP.COM/LARGE/1922000722BB18040DB5 "border=" 0 "width=" 640 "/>
Figure 5: Output of the action string
7. Data type Conversion
Various raw data types and string types can be converted to each other through methods.
The static methods of the ValueOf () series are used to convert from other objects (raw data type objects) to strings. For example:
public static String valueOf (Boolean b)
public static String ValueOf (char c)
public static String valueOf (int i)
public static String valueOf (long L)
public static String valueOf (float f)
public static String valueOf (double D)
The concrete examples are as follows:
(1) Convert from int to string.
For example:
int intvar=1;
String Strvar;
Strvar=string.valueof (Intvar);//"1"
(2) Convert from float to string.
For example:
Folat fltvar=9.99f;
String Strvar;
Strvar=string.valueof (Fltvar);//"9.99"
(3) Convert from double to string.
For example:
Duble dblvar=99999999.99
String Strvar;
Strvar=string.valueof (Dblvar);//"9.999999999E7"
(4) converting from char to string.
For example:
Char chrvar= ' a ';
String Strvar;
Strvar=string.valueof (Chrvar);//"A"
(5) Convert from string to int, float, long, double.
For example:
String intstr= "10";
String fltstr= "10.1f";
String longstr= "99999999";
String dblstr= "99999999.9";
int I=integer.parseint (INTSTR);//10
Float f=float.parsefloat (FLTSTR);//10.1
Long Lo=long.parselong (LONGSTR);//99999999
Double d=double.parsedouble (DBLSTR);//9.99999999e7
(6) Convert from string to byte, short.
For example:
String str= "0";
byte b=byte.parsebyte (str);//0
Short Sh=short.parseshort (str);//0
(7) converting from string to char.
For example:
String str= "ABC";
Char A=str.charat (0);//return character A
(8) Convert from String to Boolean.
For example:
String str= "true";
Boolean flag=boolean.valueof (str);//true
Six, StringBuffer class
The StringBuffer class provides a variable sequence of strings, similar to the string class, but it can be arbitrarily modified for stored sequences of characters, and is much more flexible to use than the string class. Its common constructors are:
StringBuffer ()
Constructs an empty StringBuffer object that has an initial capacity of 16 characters.
StringBuffer (String str)
Constructs a StringBuffer object with the initial content as a copy of the string str.
For the StringBuffer class, there are two more convenient series of methods, namely the Append method series and the Insert method series, in addition to the usual image length, string interception, and string retrieval methods used in the String class.
(1) The Append method series adds data directly to the end of the StringBuffer object based on the data type of the parameter.
Public StringBuffer Append (Boolean B)
Public StringBuffer append (char c)
Public StringBuffer append (char[] str)
Public StringBuffer append (char[] str,int offset,int len)
Public StringBuffer append (double D)
Public StringBuffer append (float f)
Public StringBuffer append (int i)
Public StringBuffer append (long L)
Public StringBuffer append (Object obj)
Public StringBuffer append (String str)
Public StringBuffer append (StringBuffer sb)
(2) The Insert Method series inserts data into the offset position of the stringbuffer based on the data type of the parameter.
Public stringbuffer Insert (int offset,boolean b)
Public stringbuffer Insert (int offset,char c)
Public stringbuffer Insert (int offset,char[] str)
Public stringbuffer Insert (int index,char[] Str,int offset,int len)
Public stringbuffer Insert (int offset,double D)
Public stringbuffer Insert (int offset,float f)
Public stringbuffer Insert (int offset,int i)
Public stringbuffer Insert (int offset,long l)
Public stringbuffer Insert (int offset,object odj)
Public stringbuffer Insert (int offset,string str)
(3) The following method is used to convert the data of a StringBuffer object into a string:
Public String toString ()
Example 6: Based on example 5 is modified, using the StringBuffer object to get the output interface shown in 6.
program file name is Teststring.java
public class TestString
{
public static void Main (string[] args)
{
StringBuffer str=new stringbuffer ("The substring begins at the specified beginindex.");
StringBuffer str1=new StringBuffer ("string");
String Str2=new string ();
int Size=str.length ();
int Flag=str.indexof ("substring");
Str2=str.substring (flag,flag+9);
StringBuffer strout=new StringBuffer ("string");
Strout.append (str);
Strout.append ("Total length:");
Strout.append (size);
int F=strout.indexof ("total");
Strout.insert (f, ' \ n ');
System.out.println (Strout.tostring ());
if (str1.tostring (). Equals (STR2))
System.out.println ("truncated string:" +str1.tostring ());
Else
System.out.println ("truncated string:" +STR2):
}
}
Figure 5/6: Output of the action string
Seven, StringTokenizer class
The StringTokenizer class is a class that implements the enumeration interface, which allows a program to divide a string into multiple tokens, by default with a space delimiter, such as dividing a string into multiple tokens, by default with a space delimiter, such as the string "This is Test "is divided into four word marks. The user can also specify a separator character. The delimiter is false, the string is split, and the delimiter is true, and the delimiter itself is used as part of the split string. Its constructors and common methods are as follows:
StringTokenizer (String str)
Constructs a StringTokenizer object as a string str.
StringTokenizer (String str,string Delim)
Use the Delim delimiter to build the StringTokenizer object with the initial string str.
int Counttokens ()
Returns the total number of tokens identified
Boolean Hasmoretokens ()
Test if there are any identified tokens.
Boolean NextToken (String delim)
Returns the next token delimited by the string Delim.
String NextToken ()
Returns the next recognized token.
Example 7: Use the StringTokenizer class to split the string, as shown in the split case 7. The source program code is as follows:
Import java.util.*;
public class Usetoken
{
public static void Main (string[] args)
{
String str= "math:: English:: Language:: Chemistry";
StringTokenizer st=new StringTokenizer (str, "::");
System.out.println (str+ "The number of courses:" +st.counttokens ());
while (St.hasmoretokens ())
{
System.out.println (St.nexttoken ("::"));
}
Str= "Hello This is a test";
St=new StringTokenizer (str);
System.out.println (str+ "\ n the number of words:" +st.counttokens ());
while (St.hasmoretokens ())
{
System.out.println (St.nexttoken ());
}
}
}
650) this.width=650; "src=" Http://p2.pstatp.com/large/19ed000112740c5989d8 "border=" 0 "width=" 564 "/>
Figure 7:stringtokenizer The result output of a segmented word
So about the Java data structure and the class has some of the problems of the small part of the introduction, more Java learning issues in the Cloud Technology Java Forum to discuss, Java Learning video material please download in the technical area (www.yunjkj.cn)
This article is from the "12268666" blog, please be sure to keep this source http://12278666.blog.51cto.com/12268666/1909689
What are the Java data structures and classes?