# Java Reading Notes # Collection framework 2

Source: Internet
Author: User
Tags sorts

# Java Reading Notes # Collection framework 2
4: Object packaging class of basic data type
(1) to facilitate operations on each basic data type, java provides many attributes and methods for us to use.
(2) Purpose:
The advantage of encapsulating basic data types into objects is that more functions can be defined in objects to operate on the data.
One of the common operations is to convert the basic data type and string.
A: Easy to operate
B: used for mutual conversion with strings
(3) Correspondence between basic data types and Object Types
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Boolean Boolean
Char Character
(4) constructor
Field Abstract:
A constant whose static int MAX_VALUE is 2 ^ 31-1. It indicates the maximum value that the int type can represent.
Static int MIN_VALUE is a constant with a value of-2 ^ 31. It represents the minimum value that can be expressed by the int type.
Static Class TYPE indicates the Class instance of the basic TYPE int.

Integer (int value) is used to construct a newly assigned Integer object, which indicates the specified int value.
Inreger (String s) Note: s must be a String of pure numbers. Otherwise, NumberFormatException occurs.

(5) several common methods
Integer. toBinaryString ();
Returns the string representation of an integer parameter in the form of an unsigned integer (base 2.
Integer. toOctalString ();
Returns the string representation of an integer parameter in the form of an unsigned integer (base 8.
Integer. toHexString ();
Returns the string representation of an integer parameter in hexadecimal notation (base 16.
Static int Integer. parseInt (String s) parses String parameters as signed decimal integers,
The string must be a numeric string within the int range.
Static int Integer. parseInt (String s, int basic)
Use the base number specified by the second parameter to resolve the string parameter to a signed integer.
The string must be a numeric string within the int range.
Short partial value () returns the value of this Integer in the short type.
Int intValue () returns the Integer value of the int type.
Static Integer valueOf (int num) returns an Integer instance that represents the specified int value.
Static Integer valueOf (String s) returns the Integer object that saves the specified String value.
Static Integer valueOf (String s, int radix)
Returns an Integer object that stores the base number provided by the second parameter.
The value extracted from the specified String during parsing.
(6) type conversion
Int -- Integer
Int num = 20;
A: Integer I = new Integer (num );
B: Integer I = Integer. valueOf (num );
Integer -- int
Integer I = new Integer (20 );
A: int num = I. intValue ();

Int -- String
Int num = 20;
A: String s = String. valueOf (num );
B: String s = "" + num;
C: String s = Integer. toString (num );
String -- int
String s = "20 ";
A: int num = Integer. parseInt (s );
B: Integer I = new Integer (s); or Integer I = Integer. valueOf (s );
Int num = I. intValue ();
5. Collection framework:
(1) Why does a collection class appear?
Objects are represented in objects. objects are stored to facilitate operations on multiple objects.
A set is the most common way to store objects.
(2) arrays and collections are both containers. What is the difference between the two?
The array length is fixed, while the set length is variable.
Array values can store objects and basic data types. A set can only store objects.
The data types in array storage are fixed, while those in set storage are not fixed.
(3) features of the Collection class:
A set can only store objects.
The length of the set is variable.
Different types of objects can be stored in a set.
(4) Collection class framework (important !!! The differences between several containers must be distinguished ):
Collection: top-level interface
| ---> List: List. The elements are ordered (the element has a badge index) and can have repeated elements or null elements.
| ---> ArrayList (JDK1.2): the underlying data structure is an array data structure, which features fast query speed (because of badge ),
However, adding or deleting an element is slow because when many elements are added or deleted, the badge of all elements must be changed.
The thread is not synchronized. The default length is 10. When the length is exceeded, the length of the set is extended by 50%.
| ---> Structured list (JDK1.2): Data Structure of the underlying data structured linked list (that is, the previous one recorded by the next element ),
Feature: the query speed is slow, because each element only knows the first element, but the addition and deletion speed is fast.
Because there are more elements, add and delete one, as long as the elements before and after it are re-connected
The thread is not synchronized.
| ---> Vector (JDK1.0): the underlying data structure is an array data structure. It features slow query and addition/deletion speeds.
The default length is 10. When the length is exceeded, the length of the set is extended by 100%.
Thread synchronization.
(The Vector function is the same as the ArrayList function and has been replaced by ArrayList)


Notes for using List!
| ---> ArrayList:
(1) When there is no requirement to store elements in the ArrayList, that is, only ordered rows are required;

(2) When elements stored in the ArrayList must not be repeated, such as student objects
If it is regarded as the same person, it is not stored in it. When defining the student object, the equals method must be rewritten.
Public boolean equals (Object obj)
{
If (! (Obj instanceof Student ))
Return false;
Student stu = (Student) obj;
Return this. name. equals (stu. name) & this. age = stu. age;
}
When a student object is saved to the ArrayList set through add, the set underlying layer calls the student-class equals method,
Duplicate students are not saved.
NOTE: For the List set, whether it is the add, contains, or remove method, determine whether the elements are the same,
They are all determined by the equals method of the replay!


| ---> Upload list
(1) Special Methods of LinkLedist:
Boolean offerFirst (E) inserts the specified element at the beginning of this list.
Boolean offerLast (E) inserts the specified element at the end of this list.
E peekFirst () is obtained but the first element in the list is not removed. If the list is empty, null is returned.
E peekLast () is obtained but the last element in the list is not removed. If the list is empty, null is returned.
E pollFirst () gets and removes the first element in the list. If the list is empty, null is returned.
E pollLast () obtains and removes the last element of this list. If this list is empty, null is returned.
(2) Special LinkLedist methods can be used to achieve special data access methods, such as stacks and queues.


In general, which List interface is used for the Implementation class?
If you want to add or delete files quickly, consider using the shortlist
If fast query is required, use ArrayList
If thread security is required, use Vector.


| ---> Set: Set. elements are unordered (because no index is available) and cannot be duplicated. It can have a null element.
| ---> HashSet (JDK1.2): the underlying data structure is a hash table, which features fast access speed, unique elements, and threads are not synchronized.
Unique principle of guarantee elements:
First, judge whether the hashCode value of the element is the same, and then judge whether the equals method of the two elements is true
(The custom elements stored in the HashSet must be rewritten with the hashCode and equals methods,
To ensure the uniqueness of elements !)
| ---> TreeSet: underlying data structured binary tree. You can sort the elements in the Set. Elements are ordered and threads are not synchronized.
The basis for ensuring element uniqueness: compareTo method return 0
The first method of TreeSet sorting: Make the elements have a comparison, for example, eight basic data types or character strings,
Implement the Compareble interface and overwrite the compareTo method,
This method is the natural sequence of elements.
The first method of TreeSet sorting: When the elements themselves do not have the comparison (such as the storage of student objects) or
When the comparison is not the comparison we need (for example, we want to sort the string length ),
In this case, the set itself needs to have a custom comparison.
So how can we make the set have a comparison? When the set is initialized,
Make the set have a comparison method. Define a class,
Implement the Comparator interface to overwrite the compare method.


Precautions for using the Set:
(1) HashSet:
The hashCode of elements stored in a HashSet in the new method is different, but we usually define the object,
For example, when a student object is a new student object, when their names and age are the same, we think
For the same object, to ensure the uniqueness of elements, we usually store elements in the HashSet set,
The hashCode and equals methods are usually rewritten in the class of the defined object.
Public int hashCode ()
{
Return name. hashCode () + age * 39;
}
Public boolean equals (Object obj)
{
If (! (Obj instanceof Student ))
Return false;
Student stu = (Student) obj;
Return this. name. equals (stu. name) & this. age = stu. age;
}


How does HashSet ensure the uniqueness of elements?
If the hashCode values of the two elements are different, the equals method is not called.
If the hashCode values of the two elements are the same, the system continues to judge whether equals returns true;
Although the hashCode and equals methods are defined in the custom object class, they are not manually called.
Instead, when storing elements in the HashSet set, the set underlying layer calls the hashCode and equals
It judges by itself the object and determines whether the two elements are the same element.


(2) TreeSet:
TreeSet requires comparison of elements stored in it; otherwise, an error is reported.
The first method of TreeSet sorting: Make the elements have a comparison
Defines the object class, implements the Compareble interface, and rewrites the compareTo method. This method is the natural sequence of elements.
Class Student implements Comparable
{
Private String name;
Private int age;
Public Student (String name, int age)
{
This. name = name;
This. age = age;
}
Public String getName ()
{
Return name;
}
Public int getAge ()
{
Return age;
}
Public int compareTo (Object obj)
{
If (! (Obj instanceof Student ))
Throw new RuntimeException ("not a student object! ");
Student stu = (Student) obj;
Int num = this. age-stu.age;
If (num = 0)
Return this. name. compareTo (stu. name );
Return num;
}
}
The first method of TreeSet sorting: Make the set have a comparison
When the element itself is not comparable (for example, when the student object is stored) or has
When the comparison is not the comparison we need (for example, we want to sort the string length ),
In this case, the set itself needs to have a custom comparison.
So how can we make the set have a comparison? When the set is initialized,
Make the set have a comparison method. Define a class,
Implement the Comparator interface to overwrite the compare method.
Class StringLengthComparator implements Comparator
{
Public int compare (Object obj1, Object obj2)
{
String s1 = (String) obj1;
String s2 = (String) obj2;
Int num = new Integer (s1.length (). compareTo (new Integer (s2.length ()));
If (num = 0)
Return s1.compareTo (s2 );
Return num;
}
}
Class TreeSetTest
{
Public static void main (String [] args)
{
TreeSet ts = new TreeSet (new StringLengthComparator ());
Ts. add ("addfg ");
Ts. add ("dfg ");
Ts. add ("agtuug ");
Ts. add ("vgjkg ");
Sop (ts );
}
}

The basic data type or string object implements the Comparable interface. Therefore, the basic data of the same type is compared, that is, the natural order.


Map: the top-level interface. This Set stores key-value pairs and the keys are unique. Map and Set are similar. The bottom-layer Set uses the Map Set.
There is no iterator for the Map Set. To retrieve elements, you must first convert the Map Set to the Set to traverse the elements.
| ---> HashTable (JDK1.0 ):
The underlying layer is the data structure of the hash table;
The null key and null value cannot be used;
The hashCode and equals methods must be implemented for the objects used as keys to ensure the uniqueness of keys.
Low thread synchronization Efficiency
| ---> HashMap (JDK1.2 ):
The underlying layer is the data structure of the hash table;
The null key and null value are allowed;
The thread is not synchronized, and the efficiency is high;
Unique element:
Principle: first determine whether the hashCode value of the element is the same, and then determine whether the equals method of the two elements is true
(The custom elements stored in the HashSet must be rewritten with the hashCode and equals methods,
To ensure the uniqueness of elements !)
Class Student {
Private String name;
Private int age;
Public Student (String name, int age ){
Super ();
This. name = name;
This. age = age;
}
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}

@ Override
Public int hashCode (){
Return name. hashCode () + age * 34;
}
@ Override
Public boolean equals (Object obj ){

If (! (Obj instanceof Student ))
Return false;
Student stu = (Student) obj;
Return this. name. equals (stu. name) & this. age = stu. age;
}
Public class HashMapDemo1 {
Public static void main (String [] args ){
Map Hmap = new HashMap ();
Hmap. put (new Student ("001", 20), "beijing ");
Hmap. put (new Student ("002", 25), "hebei ");
Hmap. put (new Student ("003", 50), "hainan ");
Hmap. put (new Student ("001", 20), "beijing ");

System. out. println (hmap. size ());
Set KeySet = hmap. keySet ();
Iterator It = keySet. iterator ();
While (it. hasNext ()){
Student stu = it. next ();
String addr = hmap. get (stu );
System. out. println (stu. getName () + "..." + stu. getAge () + ":" + addr );
}
}
}
| ---> TreeMap (JDK1.0 ):
The underlying layer is a binary tree structure;
The null key and null value are allowed;
The thread is not synchronized;
You can sort keys in the Map set.
The first method of TreeMap sorting is to make the elements have a comparison, for example, eight basic data types or character strings,
Implement the Compareble interface and overwrite the compareTo method,
This method is the natural sequence of elements.
The first method of TreeMap sorting: When the elements themselves do not have the comparison (such as the storage of student objects) or
When the comparison is not the comparison we need (for example, we want to sort the string length ),
In this case, the set itself needs to have a custom comparison.
So how can we make the set have a comparison? When the set is initialized,
Make the set have a comparison method. Define a class,
Implement the Comparator interface to overwrite the compare method.
Class Student implements Comparable {
Private String name;
Private int age;
Public Student (String name, int age ){
Super ();
This. name = name;
This. age = age;
}
Public int getAge (){
Return age;
}
Public void setAge (int age ){
This. age = age;
}
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
}
@ Override
Public int compareTo (Student stu ){
Int num = new Integer (this. age). compareTo (new Integer (stu. age ));
If (num = 0)
Return this. name. compareTo (stu. name );
Return num;
}
}


Public class HashMapDemo1 {
Public static void main (String [] args ){

Map Tmap = new TreeMap ();
Tmap. put (new Student ("001", 20), "beijing ");
Tmap. put (new Student ("002", 25), "hebei ");
Tmap. put (new Student ("003", 50), "hainan ");
Tmap. put (new Student ("001", 20), "beijing ");

System. out. println (tmap. size ());
Set KeySet1 = tmap. keySet ();
Iterator It1 = keySet1.iterator ();
While (it1.hasNext ()){
Student stu = it1.next ();
String addr = tmap. get (stu );
System. out. println (stu. getName () + "..." + stu. getAge () + ":" + addr );
}
}
}


Iterator: Iterator used to iterate the collection. The Iterator replaces Enumeration.
Differences between iterator and enumeration:
The iterator allows callers to remove elements from the collection point pointed to by the iterator during iteration using well-defined semantics.
The method name has been improved to simplify writing
LisIterator: A series of table iterators that allow programmers to traverse the list in any direction and modify the list during iteration.
Comparable: this interface forcibly sorts the objects of each class that implements it. Make the elements have a comparison
Comparator: A Comparison function that forcibly sorts an object collection to make the collection comparative.
Collections: this class is composed of static methods that operate on the collection or return the collection.
Arrays: This class contains various static methods used to operate Arrays (such as sorting and searching)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.