Java object set

Source: Internet
Author: User

I. array:

An array is a set of variables of the same type and can be referenced by a common name. Arrays can be defined as any type, which can be one-dimensional or multi-dimensional. A special element in the array is to access it by subscript. Arrays provide a convenient way to group associated information.

Note: If you are familiar with C/C ++, note that Java arrays work in different ways.

1. An array is not a set. It can only store multiple original types or object references of the same type. Arrays only store object references, not objects.

2. the array itself is an object, and the objects in Java are in the heap. Therefore, no matter whether the array stores the original type or other object types, the array object itself is in the heap.

3. Two forms of array declaration: 1. int [] arr; 2. int arr []; the former is recommended, which complies with Sun's naming rules and is easy to understand, this is an int array object, not an int primitive type.

4. It is always invalid to include the array length in the array declaration! For example, int [5] arr ;. This is because no object is instantiated during declaration. The JVM allocates space only when the array object is instantiated, which is related to the length.

5. length must be specified during Array Construction, because the JVM needs to know how much space needs to be allocated on the stack. Inverse example: int [] arr = new int [];

6. Multi-dimensional array declaration. Int [] [] [] arr; is a three-dimensional int array.

7. Construct a one-dimensional array. For example, String [] sa = new String [5];

It can be divided into two sentences: String [] sa; sa = new String [5];

8. Default Value of the original type array element. JVM automatically initializes an array of the original type when it is constructed with new without initialization. Default Value: byte, short, int, long -- 0 float -- 0.0f double -- 0.0 boolean -- false char -- '"u0000 '. (Whether the array is a member variable or a local variable)

9. The reference in the object type array is initialized to null by default. For example, Car [] myCar = new Car [10]; equivalent to myCar [0] To myCar [9] is automatically initialized to myCar [I] = null;

10. Although the object type array is initialized by default, its constructor is not called. That is to say: Car [] myCar = new Car [10]; only one myCar array object is created! No instance is created for the Car object!

11. Multi-dimensional array construction. Float [] [] ratings = new float [9] []; the length of the first dimension must be given, and the rest can be left blank, because JVM only needs to know the length of the object assigned to the variable ratings.

12. array index range. The index of each element in the array starts from 0 to length-1. Each array object has a length attribute, which saves the length of the array object. (Note that the length () method of the String object is distinguished. It is a pity that the two are not unified .)

13. Java has array subscript check. When the access is out of the index range, ArrayIndexOutOfBoundsException will run abnormally. Note that this subscript check is not performed at the Compilation Time, but at the runtime! That is to say, int [] arr = new int [10]; arr [100] = 100; such an obvious error can be compiled, but thrown at runtime!

The array subscript check in Java requires additional overhead, but it is worthwhile to balance the security because many languages are insecure when using arrays, you can access any array outside your memory block. No errors will be reported during compilation and operation, causing unpredictable consequences!

 

In Java, arrays are the most efficient storage and Random Access to object reference sequences. However
Once an array is created, its size is fixed.

· Only Arrays can hold the basic data type, and other types of containers do not have this capability.

· An array is also an object and its unique member is length. The "[]" syntax is unique for accessing array objects.
Method 1.

Ii. Arrays class

· The java. util. Arrays class has a set of static methods to provide practical functions for operating Arrays. For example:
Equal () is used to compare whether two arrays are equal; fill () is used to fill the array with a value; sort () is used to sort the array;
BinarySearch () searches for elements in sorted arrays; asList () converts arrays to List containers.

· The best efficiency of using System. arraycopy () to copy an array is that it copies objects in a shortest copy (only repeat ).
System reference ).

· The sorting of arrays involves the basic goal of Program Design: to present unchanged things (sorting algorithms)
The changing things (sorting method) are separated. Callback technology can be used to achieve this goal. Java has two types
Methods provide a comparison function: first, implement the java. lang. Comparable interface, so that the class has a "natural" Comparison
Second, the policy design mode is used to create a class that implements the java. util. Comparator interface.
Create a policy to implement the comparison function.

· Arrays. binarySearch () can quickly search sorted Arrays, but if the array is not sorted
The consequences are unpredictable.

Java 2 Container class

· Java 2 Container class libraries are divided into two concepts: Collection and a group of independent metadata.
Element (also divided into two types: List, to maintain the specific sequence of elements; Set, can not have repeated elements); second, Map, 1
Key-value Pair object.

· Disadvantages of the container class: only Object-type references can be saved, and the specific type information of objects is lost, and no
Can Save basic data types.

· The iterator is used to traverse and select objects in the sequence, without considering the underlying structure of the sequence. Java
. Util. Iterator provides the Iterator function to traverse objects in the container.

· When using containers, try to transform the specific container classes to the upper, so that the code is only applicable to Collection,
List, Set, or Map interfaces.

 

Iii. list

 

· In the Java2 container class library, two lists are implemented: ArrayList, which has the advantage of random access.
The second advantage is that the insert and delete operations are fast and can be used as stacks or queues. Both
Generally, ArrayList is preferred.

· If the iterator returned by the container class has the data modification function, all modifications will be reflected in the container.
Iv. Set
· Set has the same interface as Collection. It does not store duplicate elements and does not guarantee maintenance of elements.
. The Java2 container class library has three main container classes that implement the Set interface: HashSet, TreeSet, and
Sorted set, where HashSet is the most commonly used.

· HashSet uses a hash function, designed specifically for fast search. The objects stored in it must be defined.
Equals () and hashCode (). HashMap internally maintains data in a HashSet.

· TreeSet uses the data structure of the red/black tree to sort elements. The objects stored in the TreeSet must be sorted.
Some objects implement the Comparable interface, or pass in a Comparator in the TreeSet constructor. TreeSet
It is actually the only implementation of SortedSet. TreeMap internally maintains data in the TreeSet.

· LinkedHashSet uses hashes internally to speed up query, while using a linked list to maintain the storage of Elements
Order (the order of element insertion), but the objects stored in it must define equals () and hashCode ().

 

V. MAP:

· HashMap is based on the implementation of a hash (replacing Hashtable), and inserts and queries an open key-value pair.
Pin is fixed. HashMap is the most commonly used Map.

· LinkedHashMap is similar to HashMap, but the iteration time is used. The obtained "key-Value Pair" is its insertion time.
Or LRU order.

· TreeMap is based on the implementation of the Red and black trees. During iteration, the keys or key values are sorted by Comparable.
Or Comparator ).

· WeakHashMap and IdentityHashMap are designed to solve special problems.

· The data behind the Collection (keySet or values method) returned by Map is still supported by Map.
Any changes to the Collection are reflected in the Map.

· Elements (or keys) stored in containers that use Hash data structures, such as HashMap and HashSet
) The equals () and hashCode () Methods of the Object must be overwritten at the same time. Otherwise, the unique effect cannot be guaranteed.
Because both methods in the Object use the Object address, the memory address is always different. In addition,
HashCode () does not always return a unique identifier code, but equals () must be able to strictly determine whether two objects are
No.

· Considerations when designing hashCode (): 1. generate the same value for the same object; 2. Do not rely on
Unique object information (such as the object address); 3. It must be meaningful. It is best to generate a hash code based on the content.
4. Try to make the hash code distribution even. (In general, write the correct hashCode and equals for the class.
Skills are required)

· If you want to hold references to an object and want the Garbage Collector to release them, you should
Use the Reference class in the java. lang. ref package.

· WeakHashMap is a storage space-saving container that allows the Garbage Collector to automatically clear
There are common referenced "keys" and "values ". In fact, WeakHashMap automatically uses WeakReference to encapsulate
Each "key" object.

· Just like the Arrays class, Collections provides some static functions for convenient Collection or List operations.
State method. In particular, it also provides a series of ummodifiableXXX methods to return a "read-only" Set,
List or Map container.

· Java containers have a protection mechanism that prevents multiple processes from simultaneously modifying the content of the same container. For example
If you modify the object of a container while traversing a container through iteration, an exception is thrown. Therefore
You must modify the container before obtaining the iterator.

· The List returned by the Arrays. asList () method is not of the java. util. ArrayList type and does not support add,
Remove, clear, and other modification methods, but you can use the set method.

· In new programs, outdated Vector, Hashtable, and Stack containers should no longer be used.

Address: http://blog.csdn.net/lyflower/article/details/4206500

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.