Java Basics--collections

Source: Internet
Author: User
Tags addall set set sorts

Storage objects can be considered: arrays, collections
Array Storage object features: student[] stu = new student[23]; Str[0] = new Student ();
Cons: 1. Once created, its length cannot be changed
2. The number of objects that a real array holds is not known.
The Java collection can be divided into collection and map two systems:
Collection interface:

  List interface: ordered, repeatable elements equal to "dynamic" arrays
The class in which the element (or object) is added into the list collection must override the Equals () method;
    |---ArrayList (The main implementation class)
   |---linkedlist(more suitable for frequent insertions, deletions)
   |---Vector(Old implementation class, thread-safe, but less efficient than ArrayList)
 set interface: store unordered, non-repeating elements

1. Disordered sex! = randomness, which means that the elements are stored in a disordered position in the underlying
2. Non-repeatability when you want to add the same elements to the set, the following additions do not go in
    Note: The same judgment of non-repeatability, according to the Equals () and Hashcode () methods in the class where the elements in the set are added, so be sure to override the Equals () and Hashcode () methods.

    

    |---HashSet: Main Implementation class
   |---linkedhashset: HashSet subclasses, when we traverse the collection elements, are carried out in the order in which they are added, with frequent traversal, with fewer additions and insertions
    |---TreeSet: You can sort by the specified attributes of the elements added to the collection

1. The elements added to the treeset must be of the same class
2. You can traverse in the order specified by the elements added into the collection. Like string, wrapper class, etc. by default in order to traverse from small to large
3. When you add an object to a custom class to TreeSet, there are two sorting methods:1. Natural sort 2. Custom sorting

Natural Sort: 1. The class that requires the element to be added into the TreeSet implements comparable interface
2. Overrides the abstract method for its compareto (Object obj), which indicates which property to sort by
3. Add elements to TreeSet, and if this interface is not implemented, run-time exceptions are reported
Custom Sort: 1. Create a class object that implements the comparator interface, overriding the comparator Compare () method in the implementation class
2. Indicate that the customer          Sort
3. The implementation class object that implements the comparator interface is passed as a parameter to the constructor of TreeSet
4. Add an element to TreeSet, and if this interface is not implemented, the runtime exception is reported
Requires the overridden CompareTo () method or compare () method to conform to the hashcode () and Equals () methods of the added class

public void Testtreeset () {//1. Create a class object that implements the Comparator interface, overriding the Compare () method Comparator com = new Comparator () {//To Treese T to add an object of the customer class, in this compare () method, to indicate which property of the customer is ordered by the public int compare (object O1, Object O2) {if (O1 ins                Tanceof customer && O2 instanceof customer) {Customer C1 = (customer) O1;                Customer C2 = (customer) O2;                int i = C1.getid (). CompareTo (C2.getid ());                if (i = = 0) {//two elements have the same ID as return C1.getname (). CompareTo (C2.getname ());            } return i;        } return 0;    }    };    2. Pass this object as a parameter to TreeSet in the constructor of TreeSet set = new TreeSet (COM);    3. Add the object Set.add of the class involved in the Compare () method in the comparator interface to TreeSet (new Customer ("AA", 12));    Set.add (The New Customer ("DD", 23));    Set.add (New Customer ("EE", 42));    Set.add (New Customer ("GG", 25));    Set.add (New Customer ("CC", 22));    Set.add (The New Customer ("DD", 55));       for (Object Str:set) { System.out.println (str);                 }}

Note: Natural sorting and custom sorting if two are implemented, custom sorting takes precedence.


Map interface: The collection of "key-value" pairs
Key is non-repeatable, stored with set, value is repeatable, stored with collection.
A key-value is a Entry (map.entry), Entry is stored using set.

  |---HashMap: The main implementation class of map

HashMap the criteria for determining the equivalent of two keys is that two keys return true,hashcode values by means of the Equals () method are also equal.
HashMap the criterion for determining the equality of two value is: Two value returns true through the Equals () method.
  |---linkedhashmap: HashMap subclasses that use linked lists to maintain the order in which they are added into the map. When traversing, they are traversed in the order in which they were added.
  |---TreeMap: sort by 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 (value is not required, type can be different)
    For key: Natural sort vs Custom sort
  |---HashTable: old implementation class, thread safe, can not add null key, null value, not recommended
Subclass: Properties: commonly used to process property files , both keys and values are of type string

Use properties to process property files public void Test () {    Properties Pros = new properties ();    Pros.load (New FileInputStream ("Jdbc.properties"));//jdbc.properties stored user=root,password=123abc    String user = Pros.getproperty ("user");    SYSTEM.OUT.PRINTLN (user);//root    String password = pros.getproperty ("password");    SYSTEM.OUT.PRINTLN (password);//123ABC}

  

1. Common methods in the collection:
1.size ();
2.add (Object obj);
3.addAll (Collection coll);
4.boolean IsEmpty ();
5.clear ();
6.boolean contains (Object obj);//equal return True, unequal return false;
Judging by: According to the Equals () method of the class in which the element resides, it is generally required to override the Equals () method of the Class)
    Explicit: If the element in the collection is a custom class object, ask: Custom class to override the Equals () Method!
7.containsAll (Collection coll);//Determines whether the current collection contains all of the elements in Coll
8.coll1.retainall (Collection coll2);//Find the elements shared by COLL1 and Coll2, return to COLL1
9.boolean Remove (Object obj);
10.boolean Coll1.removeall (Collection coll2);//Remove elements from the coll2 from Coll1 and return to COLL1
11.coll1.equals (Collection coll2);
12.hashCode ();
13.Object obj = Coll.toarray ();//convert collection to array
14.iterator ();//Returns an Iterator interface implementation class object for collection collection traversal (cannot traverse map)
2. Traversal of the collection:

1. Using Iterator iterator implementation: Iterator ite = Coll.iterator ();    while (Ite.hasnext) {    System.out.println (Ite.next ());}
2. Use the enhanced for loop to implement traversal of collections and arrays: for (Object i:coll) {    System.out.println (i);    i = 23;//Here i is a newly defined local variable whose worth modification does not affect the coll itself (Value passing)}

New additions to the 3.List in relation to collection:
void Add (int index, Object ele)
Boolean addall (int index, Collection eles)
Object get (int index)
int indexOf (Object obj)
int lastIndexOf (Object obj)
Object Remove (int index)
Object Set (int index, Object ele)
List sublist (int fromIndex, int toindex)

The Arrays.aslist (...) method returns a List collection that is neither an ArrayList instance nor a Vector instance. Arrays.aslist (...) The return value is a fixed-length List collection


4.Map Common methods:
4.1 Add, delete operations:
Object Put (object Key,object value)
Object Remove (Object key)
void Putall (Map t)
Void Clear ()

4.2 element query operation:
Object Get ( Object key)
Boolean ContainsKey (Object key)
Boolean Containsvalue (object value)
int size ()
Boo Lean IsEmpty ()
Boolean equals (Object obj)


4.3-tuple view how to:
Set keySet ()
Col Lection values ()
Set entryset ()

Traverse key Set Set set = Map.keyset (); for (Object obj:set) {    System.out.println (s);} Traverse the value set collection value = Map.values (), Iterator i = Value.iterator (), while (I.hasnext ()) {    System.out.println ( I.next ());}
Traverse Key-value to
Mode one: By combining keyset () with the Get () method
Set set = Map.keyset ();
for (Object Obj:set) {
System.out.println (Map.get (obj));
}
Mode two: Using the EntrySet () method:
Set set = Map.entryset ();
for (Object Obj:set) {
Map.entry Entry = (map.entry) obj;
System.out.println (Entry.getkey () + "" + Entry.getvalue ());
SYSTEM.OUT.PRINTLN (entry);//output is an equal sign connected to the Key-value
}

Tool class for

action Collection: Collections
differs from collection

sort operation: (all static method)
Reverse (list): Reverses the order of the elements in the list
Shuffle (list): Randomly sort the list collection elements
Sort list: Sorts the specified list collection elements in ascending order according to the natural ordering of the elements
sort (Lis T,comparator): Sorts the List collection elements according to the order of the specified Comparator
Swap (list,int, int): Swaps the I and J elements in the specified list collection
Find and replace
Object Max (Collection): Returns the largest element in a given set, based on the natural order of the element
Object Max (Collection,comparator): According to Comparat Or in the order specified, returns the largest element in the given collection
Object min (Collection)
Object min (collection,comparator)
int frequency (collecti On,object): Returns the number of occurrences of the specified element in the specified collection
void copy (List dest,list src): Copy content from src to dest
Boolean replaceall (list List,obje CT oldval,object newval): Replaces all old values of the List object with the new value

List list1 = new ArrayList (); List1.add (123); List1.add (332); List1.add (2332);//list1 copy list list2 to List2 = new ArrayList () ;//Wrong way, because at this time the length of the List2 is 0List list2 = arraylist.aslist (New Object[list1.size ()]); Collections.copy (List2, List1);

Synchronization control: Troubleshooting Thread-safety issues when multithreading concurrently accessing collections
Multiple synchronizedxxx () methods are available in the collections class to wrap the specified collection as a collection of thread synchronizations
List List1 = new ArrayList ();//list1 is not thread-safe
List List2 = collections.synchronizedlist (list1);//list2 is thread-safe

Java Basics--collections

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.