Basic Java Learning: a collection of articles

Source: Internet
Author: User
Tags addall sorts

1. What is a collection?

1.1 Overview of the Java collection: On the one hand, object-oriented language to the embodiment of the object is in the form of objects, in order to facilitate the operation of multiple objects, it is necessary to store objects, on the other hand, the use of array storage objects have some drawbacks, and the Java collection is like a container, You can dynamically put references to multiple objects in a container

The 1.2 Java Collection class can be used to store multiple objects of varying amounts, and can be used to hold associative arrays that have a mapping relationship

1.3 Storage objects can be considered: ① array ② Collection

1.4 Characteristics of the array storage object: student[] stu = new STUDENT[20]; Stu[0] = new Student ();

> Cons: ① once created, its length is immutable ② the number of objects the real array holds is unknowable

1.5 Java collection can be divided into collection and Map of two systems

> Collection Interface: Set: unordered, non-repeatable collection of elements, List: Elements ordered, repeatable collections

> Map Interface: A collection of "key-value pairs" with a mapping relationship

2.Collection

2.1 The method under the Collection interface:

> Size (): Returns the number of elements in the collection

> Add (Object obj): Adds an element to the collection

> AddAll (Collection coll): Adds all the elements contained in the formal parameter coll to the current collection

> IsEmpty (): Determines whether the collection is empty

> Clear (): empties the collection element

> contains (Object obj): Determines whether the specified obj element is contained in the collection. If included, returns True, in turn returns false, the basis of judgment: based on the Equals () method of the class where the element is located, it is clear: if the element in the collection is the object of the custom class. Requirement: Custom class to override Equals () method

> Containsall (Collection coll): Determines whether the current collection contains all of the elements in Coll

> Retainall (Collection coll): The element that is common to the current collection and Coll, returned to the current collection

> Remove (Object obj): Deletes the obj element in the collection, returns true if the deletion succeeds, or false

> RemoveAll (Collection coll): Removes elements contained in Coll from the current collection

> Equals (Object obj): Determines whether all elements in the collection are identical

> hashcode (): Returns the hash value of the array

> ToArray (): Convert a collection to an array

> Iterator (): Returns an object of an Iterator interface implementation class

  @Test  public  void   Test ()    {Collection coll  = new   ArrayList ();    Coll.add ( 123 new  String ("AA"  new   Date ());    Coll.add ( "BB"  new  person ("MM", 23 = Coll.iterator ();  while   (I.hasnext ()) {System.out.println ( I.next ()); } }
3.List

3.1 List: Elements that are stored in an orderly, repeatable manner

The main implementation class of the 3.2 arraylist:list, which is an array implementation, is traversed using this implementation

> Add (int index, Object ele): Adds an element at the specified index position index ele

> addall (int index,collection eles): Adds an element collection at the specified index position index

> get (int index): Gets the element of the specified index

> indexOf (Object obj): Returns the position where obj first appeared in the collection, no, 1

> lastIndexOf (Object obj): Returns the position of the last occurrence of obj in the collection, no, 1

> Remove (int index): Deletes the element at the specified index position

> Set (int index,object ele): Sets the element at the specified index position to Ele

> sublist (int fromindex,int toindex): Returns a sub list that ends from FromIndex to Toindex

3.3 LinkedList: It is recommended to select this implementation class for frequent insert and delete operations

3.4 Vector: Thread-safe, not recommended

4.Set

4.1 Set: Stores unordered, non-repeating elements, and the methods commonly used in set are defined under collection.

> Disorder: Disorder! = randomness, true disorder, refers to the location of an element in the underlying storage is unordered

> Non-repeatable: When adding the same element to the set, this cannot be added in the back

> Description: The class in which the elements in the set are required to be added, be sure to override the Equals () and Hashcode () methods to ensure the non-repeatability of the elements in the set

How are the elements in the > set stored? A hashing algorithm is used: When an object is added to a set, the Hashcode () method of the class that contains the object is called first, and the hash value of this object is computed, which determines where the object is stored in set, and if there is no object storage before this location, the object is stored directly in this location. If an object is already stored at this location, then the two objects are compared by equals (). If it is the same, the latter object cannot be added, in case it returns false. Requirements: The Hashcode () method is consistent with the Equals () method

The main implementation class of 4.2 Hashset:set

4.3 linkedhashset: Using a linked list maintains a sequence of additions to the collection, which causes us to traverse the Linkedhashset collection elements in the order they were added, which is the subclass of HashSet, It determines where the element is stored, based on the hashcode value of the element, but it maintains the order of the elements using the linked list, which makes the elements appear to be saved in the order of insertion, with the performance of the insert being slightly lower than hashset, but with good performance when iterating through all the elements of the set, which does not allow the collection elements to repeat

4.4 TreeSet: The element that is added to it must be the same class, which can be traversed in the order specified by the elements added to the collection, such as String, wrapper class, etc. by default, in order from small to large, there are two sorting methods ① natural sorting when adding objects to the custom class to TreeSet ② Custom sorting, natural sorting requires that the custom class implement the Java.lang.Comparable interface and override its CompareTo (Object obj) in this method, indicating which property of the custom class to sort by, and when adding elements to TreeSet, The first comparison is based on CompareTo (), and once you return 0, although this property is the same for only two objects, the program considers the two objects to be the same, and the latter object cannot be added. Ps:compareto () consistent with hashcode (), Equals (), custom sort: Implement Comparator interface

 Public voidtest{Comparator com=NewComparator () { Public intCompare (Object o1,object O2) {if(O1 instanceof Customer &&O2 instanceof Customer) {Customer C1=(Customer) O1; Customer C2=(Customer) O2; inti =C1.getid (). CompareTo (C2.getid ()); if(i = =0){                     returnc1.getname (). CompareTo (C2.getname ()); }                returni; }            return 0; }} TreeSetSet=NewTreeSet (COM); Set. Add (NewCustomer ("AA",1003)); Set. Add (NewCustomer ("BB",1002)); Set. Add (NewCustomer ("GG",1004)); Set. Add (NewCustomer ("CC",1001)); Set. Add (NewCustomer ("DD",1001));  for(Object str:Set) {System. out. println (str); }   }       
5.Map

5.1 Map and collection, used to save the mapping of the Key-value,map in the key and value can be any reference type of data, the key in the map is set to store, do not allow repetition, that is, the same map object corresponding to the class, The hashcode () and Equals () methods must be overridden, and the commonly used string class as the "key" of the map, there is a one-way relationship between key and value, that is, the specified key can always find a unique, deterministic value

The main methods under the 5.2 map interface are:

> Put (Object key,object value): Add an element to the map

> Remove (Object key):

> Putall (Map t):

> Clear (): Clear map

> Get (Object key): Gets the value of the specified key and returns null if no key is available

> ContainsKey (Object key):

> Containsvalue (Object value):

> Size (): Returns the length of the collection

> Equals ():

5.3 HashMap parsing: Key is stored with set, cannot be duplicated. Value is stored with collection, can repeat a key-value pair, is a entry. All entry are stored with set and cannot be duplicated, when adding elements to HashMap, the Equals () method of the class where key is called is used to determine whether the two keys are the same, and if they are the same, they can only be added after the added element.

5.4 How to traverse a map:

> Set KeySet (): Returns the key collection for the map collection

> Collection VALUES (): Returns the value collection of the Map collection

> Set EntrySet (): Returns the entry of the map collection

5.5 Linkedhashmap: Use the list to maintain the order of the added into the map, so when you traverse the map, it is traversed in the order added.

5.6 TREEMAP: Sorts according to the specified attribute of the key that is added to the element in the map. Requirement: Key must be an object of the same class, for key: Natural sort, custom sort

5.7 Hashtable:hashtable is an ancient map implementation class, thread-safe, unlike HashMap, Hashtable does not allow NULL as key and value, as with HashMap, Hashtable also cannot guarantee the order of the Key-value pairs, Hashtable judge two keys equal, two value equals the same standard as HashMap.

5.8 The tool class for the set of Operations Collections:collections is a tool class that operates sets, lists, and maps, and collections provides a series of static methods for sorting, querying, and modifying collection elements. It also provides methods for setting immutable collection objects, synchronizing control of collection objects, and so on.

> Sort operations:

> Reverse (List): Reverses the order of the elements in the list

> Shuffle (list): Randomly sort the elements of a List collection

> Sort (list): Sorts the specified List collection in ascending order based on the natural ordering of the elements

> Sort (list,comparator): Sorts the List collection elements according to the order in which the specified Comparator is produced

> Swap (list,int,int): Swaps the I and J elements in the specified list collection

> Find, replace

> Max (Collection C): Returns the largest element in a given set, based on the natural ordering of the elements

> Max (Collection c,comparator): Returns the largest element in a given set, based on the order specified by Comparator

> min (Collection C): Returns the smallest element in a given set, based on the natural ordering of the elements

> min (Collection c,comparator): Returns the smallest element in a given set, based on the order specified by Comparator

> Frequency (Collection c,object O): Returns the number of occurrences of the specified element in the specified collection

> Copy (List dest,list src): Copy content from SRC to dest

> ReplaceAll (List list,object oldval,object newval): Replace all old values of list objects with new values

    

    

Basic Java Learning: a collection of articles

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.