Data structure is a basic programming structure for implementing a set

Source: Internet
Author: User

@ Data structure

Data structure is a basic programming structure for implementing a set

The collection frame diagram in Java:

-Collection Interface: 6 interfaces (short dashed lines), representing different collection types, is the basis of the collection framework. -Abstract class: 5 abstract classes (long dashed lines), partial implementations of the collection interface. Can be extended to custom collection classes.

-Implementation classes: 8 Implementation classes (solid line representations), specific implementations of interfaces.

2.Java Container Class Introduction①java container classes can automatically adjust their size. The ②collection interface is a set of objects that allow duplicates. The ③set interface inherits Collection, does not allow repetition, and uses one of its own internal arrangement mechanisms. The ④list interface inherits Collection, allows repetition, places elements in the order in which they are placed, and does not rearrange.

The ⑤map interface is a pair of key-value objects that hold some key-value pairs. There cannot be duplicate keys in the map. have their own internal arrangement mechanism.

3.Collection InterfaceBasic Operations-add element Add (Object obj); AddAll (Collection c);-Removes the element remove (Object obj); RemoveAll (Collection c);-seeking the intersection of Retainall (Collection c); Collection is the most basic set interface, all classes that implement the collection interface must provide two standard constructors: the parameterless constructor is used to create an empty collection, and there is a The constructor of the collection parameter is used to create a new collection that has the same type of elements as the incoming collection.
ImportJava.util.ArrayList;ImportJava.util.Arrays;ImportJava.util.Collection;ImportJava.util.Collections;ImportJava.util.List; Public classaddinggroups { Public Static voidMain (string[] args) {collection<integer> Collection =NewArraylist<integer> (Arrays.aslist(1, 2, 3, 4, 5));       Integer[] moreints={6,7,8,9,10}; Collection.addall (Arrays.aslist(moreints)); for(Integer i:collection) System. out. print (i + ","); }}
Result: 1,2,3,4,5,6,7,8,9,10, which shows the 2 usages of the collection interface, first, the collection constructor takes another collection (List) as the parameter to initialize it. Next, call the AddAll () method to add the element, noting that the method accepts only another collection as a parameter. Also, it is important to note that the collection interface does not provide a get () method for random access elements. Because collection includes set, set maintains its own internal order. If you want to examine the elements in the collection, you must use iterators. 4.List Interface4.1 List Interface The list is an ordered collection, using this interface to precisely control where each element is inserted. The user is able to access the elements in the list using an index (where the element is positioned in the list, similar to an array subscript), similar to an array of java. Unlike the set mentioned below, the list allows the same elements. In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface. Listiterator has a number of add () methods that allow you to add, delete, set elements, and traverse forward or backward.4.2 LinkedList class The LinkedList implements a list interface that allows null elements. Additionally LinkedList provides an additional Get,remove,insert method at the first or the tail of the LinkedList. These operations make the LinkedList available as a stack (stack), queue, or two-way queue (deque). This implementation is not synchronous.4.3 ArrayList class ArrayList implements a variable-size array. It allows all elements, including null. Size,isempty,get,set method run time is constant. But the Add method cost is the allocated constant, and adding n elements requires an O (n) time. Other methods run at a linear time. Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity automatically increases as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency. This implementation is not synchronous. 5.Set Interface5.1 Set interface The set has exactly the same interface as the collection, without any additional functionality. It is a collection that contains no duplicate elements, that is, any two elements E1 and E2 have E1.equals (E2) =false,set have a maximum of one null element. Obviously, the constructor of a set has a constraint that the passed-in collection parameter cannot contain duplicate elements. Note: Variable objects (Mutable object) must be handled with care. If a mutable element in a set changes its state, causing Object.Equals (Object) =true will cause some problems.5.2 HashSetThis class implements the set interface, which is supported by a hash table (actually a HashMap instance). It does not guarantee the set's iteration order, especially it does not guarantee that the order is constant. This class allows the use of NULL elements. This class provides stable performance for basic operations, and this implementation is not synchronous.5.3 LinkedhashsetA hash table and a link list implementation of a set interface with predictable iteration order. The difference between this implementation and HashSet is that it maintains a double-link list that runs on all items. This list of links defines the order of iterations, that is, the order in which the elements are inserted into the set (insert order). Note that the insertion order is not affected by the element that is reinserted in the set. This implementation is not synchronous.5.4 TreeSetNavigableset implementation based on TreeMap. The elements are sorted using the natural order of the elements, or sorted according to the Comparator provided when the set was created, depending on the construction method used. This implementation provides a guaranteed log (n) time overhead for basic operations (add, remove, and contains). This implementation is not synchronous. 6.Map InterfaceNote that map does not inherit the collection interface, and map provides a key-to-value mapping. A map cannot contain the same key, and each key can only map one value. The map interface provides views of 3 collections, and the contents of the map can be treated as a set of key sets, a set of value collections, or a set of key-value mappings.6.1 WeakhashmapA hash table-based map implemented with weak keys. In Weakhashmap, when a key is no longer in normal use, its entry is automatically removed. More precisely, for a given key, the presence of its mapping does not prevent the garbage collector from discarding the key, which makes the key a terminating, terminated, and then recycled. When a key is discarded, its entry is effectively removed from the map, so the behavior of the class differs from the other map implementations. This implementation is not synchronous.6.2 TreeMapThe mapping is sorted according to the natural order of its keys, or sorted based on the comparator provided when the mapping was created, depending on the construction method used. This implementation is not synchronous.6.3 HashMapThe implementation of a hash table-based map interface. This implementation provides all the optional mapping operations and allows NULL values and NULL keys to be used. (The HashMap class is roughly the same as Hashtable except for non-synchronous and null-allowed use.) This class does not guarantee the order of the mappings, especially because it does not guarantee that the order is constant. This implementation is not synchronous.6.4 SortedMapFurther provides a map of the overall ordering of the keys. The mapping is sorted according to the natural order of its keys, or by the comparator that are typically provided when an ordered map is created. This order is reflected when iterating over the collection view of an ordered map (returned by the EntrySet, KeySet, and Values methods). To use this sort method, you also need to provide some additional action (this interface is the corresponding mapping for SortedSet). 7. Aggregation class Performance Efficiency summaryNote that the classes shown here are non-thread safe. If you need to consider thread safety, you should use Concurrentmap,copyonwritearraylist,copyonwritearrayset and so on.
Interface Implementation class Keep the Insertion Order Repeatable Sort Instructions for use
List ArrayList Y Y N Longer than random access elements, but inserting and deleting elements is slow (array attributes).
LinkedList Y Y N Inserts, deletes elements faster, but accesses slowly (list attributes).
Set HashSet N N N Using hashing, the quickest way to get an element.
TreeSet N N Y Stores elements in a red-black tree data structure. The default is ascending.
Linkedhashset Y N N Use a hash to maintain the insertion order of elements using a linked list.
Map HashMap N N N Use hashing to provide the fastest search technology.
TreeMap N N Y The default is to save the key in ascending order of comparison results.
Linkedhashmap Y N N Save the key in the order in which it was inserted, and use the hash to increase the lookup speed.
Summary ① If you are involved in stacks, queues and other operations, you should consider using list. If you want to do a lot of random access, you should use ArrayList, and if you frequently insert and delete operations, use LinkedList. ②hashmap is designed for quick access, while TreeMap keeps the "key" always in the sorted state, so there is no hashmap fast. Linkedhashmap preserves the order in which elements are inserted, but also provides quick access through hashing. ③set does not accept duplicate elements. HashSet provides the fastest query speed, while TreeSet keeps elements in a sorted state. Linkedhashset saves the element in an insertion order. ④ the operation of the hash table, the object to be key is to rewrite the Equals and Hashcode methods correctly. ⑤ try to return the interface rather than the actual type (for abstract programming), such as returning a list instead of ArrayList, so that if you later need to change ArrayList to LinkedList, the client code does not have to be changed. Obsolete vector\hashtable\stack should not be used in ⑥ programs. The above content is reproduced to http://zhangjunhd.blog.51cto.com/113473/69677

Data structure is a basic programming structure for implementing a set

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.