Java Collection framework and java Collection

Source: Internet
Author: User

Java Collection framework and java Collection

Java Collection framework
1. java Collection framework Overview
Java SE contains a java Collection Framework (JCF) composed of a group of classes and interfaces. Its main function is to organize stored data in a certain structure, and access the data in a specific way. The goal is to provide a general framework for processing object sets, reducing the coding workload when programmers process different object sets.
Some differences in the Collection class include not only whether they support repeated element operations, but also whether the elements are ordered and whether null elements can be added. Based on these three differences, the java Collection framework divides the object storage methods into three types:
1. Set: the objects in the object container have no sequence and cannot be repeated.
2. List: objects in the object container are sorted by index order and can have repeated objects.
3. Map: the elements in the object container contain a pair of "key object-value object" mappings. The middle-key objects cannot be repeated, and the value objects can be repeated.
To support object sorting and traversal access operations, the java Collection framework provides several interfaces:
1. The SortedSet interface provides the filming function for the Set container.
2. SortedMap provides the sort of key objects for Map-type containers.
3. Interfaces Comparable and comparator are used to sort objects in a collection.
2. Collection interface and Iterator Interface
The Collection interface defines some basic methods for Collection objects.

Method Description
Int size () Returns the number of elements contained in the current set.
IsEmpyt () Determine whether the collection contains elements
Boolean contains (Objact o) Determines whether the collection contains a specified element.
Add (Objact o) Add an element to a collection
Remove (Objact o) Deletes an element from a collection.
Iterator iterator () Returns a traversal tool to access each element in the set.

 

 

 

 

 

 

 

The Iterator interface is an interface used to traverse a set.

Methods In the Iterator Interface
Method Description
HasNext () If there are more elements in the Set, this method returns true.
Next () Returns the next element in the set.
Remove () Delete the last element returned by Iterator

 

 

 

 


1. List Interface
The List interface inherits from the Collection interface, which has the following features:
1. The elements in the List are ordered.
2. List usually allows repeated elements.
3. The List Implementation class usually supports the null element.
4. You can access the elements in the List object container through indexes.
The most common implementation classes of the List interface are the ArrayList class and the List class.

1). ArrayList

Program instance:

package lei;        import java.util.ArrayList;    import java.util.List;        public class Test {        public static void main(String[] args) {                      List list = new ArrayList<>();            list.add(1);            list.add("zhangsan");            list.add(false);            list.add('a');            list.add(0, "lisi");            list.add(1);            list.remove(1);            list.remove(2);            list.set(0, "wangwu");            for (int i = 0; i < list.size(); i++) {                System.out.println(list.get(i));            }        }    }

The equals () method defined by the Object class returns true only when the Object passed to this method is the same as the Object that calls this method. You can rewrite the equals () method to treat two objects in the same state as the same object.

2). Upload list

Method Description
Void addFirst Add an object at the beginning of the linked list
Void addLast Add an object to the end of the linked list
GetFirst () Returns the first element in the linked list.
GetLast () Returns the last element in the linked list.
RemoveFirst () Delete the first element in the linked list
RemoveLast () Delete the last element in the linked list.

 

 

 

 

 

Program instance:

package lei;        import java.util.LinkedList;    import java.util.List;        public class Test2 {           public static void main(String[] args) {             LinkedList l=new LinkedList<>();            l.add("zhangsan");            l.add("lisi");            l.addFirst(1);            l.addLast(4);            System.out.println(l.getFirst());            System.out.println(l.getLast());            l.removeFirst();            l.removeLast();            for (int i = 0; i < l.size(); i++) {                System.out.println(l.get(i));                }            }    }

Selection of rule list and ArrayList
If the list needs to be quickly accessed, but the element insertion and deletion operations are not often performed, it is better to select ArrayList. If you need to perform frequent insertion and deletion operations on the list, then you should select the upload list.
2. set Interface 
The set interface inherits from the Collectiion interface and all methods of the Collection interface. The set interface has the following features:
1. The Set type container cannot contain duplicate elements. When an element is added to a container, you must compare whether the content of the element exists repeatedly. Therefore, the object added to the Set object container must override the equals () method.
2. elements can be ordered or not ordered.
3. Because the elements may have no order, you cannot access the fee elements in the Set Based on the subscript.
The HashSet class and TreeSet class are most commonly used to implement the Set interface.
1). Hashset
The Hashset class is implemented based on the Set interface of the hash algorithm. It has the following features:
1. When traversing a Hashset, the elements in the Hashset have no order.
2. duplicate elements are not allowed in Hashset. The repeated elements here refer to the two objects with the same hash code and compared with the equals () method, return true.
3. Allow null elements.
If the class we write re-defines the equals method, this class must also re-define the hashCode () method, and ensure that when the two objects use the equals method to compare the result to true, the return values of the hashCode () method of these two objects are equal.
Program instance:

package lei;        import java.util.HashSet;    import java.util.Set;        public class Test4 {           public static void main(String[] args) {            Set<String> set=new HashSet<String>();            set.add("zhangsan");            set.add("lisi");            for(String s:set){                System.out.println(s);            }        }    }

2). TreeSet
The TreeSet class not only implements the Set interface but also the SortedSet interface to ensure that the objects in the Set are sorted in a certain order. When an object is added to the TreeSet set, it is inserted into the ordered object sequence, but this sorting is not in the order of object addition, instead, they are sorted by certain algorithms.
TreeSet uses the natural sequence of elements to sort the elements, or sorts the elements based on the Comparator provided when the Set is created. TreeSet supports natural sorting and custom sorting.
3. Map Interface
The Map interface is another important interface different from the Collection interface in the java Collection framework. It corresponds to a Key-to-Value interface). Two groups of objects are saved in the Map object container. One group is used to save the Key in the Map, and the other group is used to save the Value. Key and Value can be upgraded to any data of reference type. The Key cannot be repeated, but the Value can be repeated.
1). HashMap
HashMap is an implementation of the Map interface based on the hash algorithm. HashMap stores its key in the hash table for maintenance. The key is unique. However, HashMap does not guarantee that keys are arranged in a specific order, especially that the order remains unchanged permanently.
The HashMap class implements the Map interface and thus has all the methods of the Map interface.

Package day1228; import java. util. *; public class HashMapDemo {public static void main (String [] args) {// create a new HashMap Map <String, String> map = new HashMap <String, string> (); map. put ("a1", "xiao"); map. put ("b2", "xiaol"); map. put ("a4", "xiaosd"); map. put ("b1", "12a"); map. put ("a3", "1"); // use iterator to traverse the key and value System. out. println ("the previous Map value is:"); Set <String> keys = map. keySet (); for (Iterator <String> I = keys. iterator (); I. hasNext ();) {String key = I. next (); String value = map. get (key); System. out. println (key + "=" + value);} // Delete the System with the key "a4. out. println ("\ n elements whose key value is a4"); map. remove ("a4"); // use iterator to traverse the key and value System. out. println ("Map value after \ n:"); keys = map. keySet (); for (Iterator <String> I = keys. iterator (); I. hasNext ();) {String key = I. next (); String value = map. get (key); System. out. println (key + "=" + value );}}}

2). TreeMap
TreeMap class is implemented based on the Map interface of the red/black tree algorithm. The storage mode of the TreeMap key is similar to that of the TreeSet. It stores the keys in the tree. The keys are arranged in natural or custom order.
Program instance:

Package day1228; import java. util. *; public class TreeMapDemo {public static void main (String [] args) {// create a new TreeMap Map <Integer, String> map = new TreeMap <Integer, string> (); map. put (1, "one"); map. put (2, "two"); map. put (3, "three"); map. put (4, "four"); map. put (5, "five"); // use iterator to display the key and value System. out. println ("the previous map value is:"); Set <Integer> keys = map. keySet (); for (Object key: keys) {String value = map. get (key); System. out. println (key + "=" + value);} // Delete the System. out. println ("\ n deleting elements with a key value of 3"); map. remove (3); // use iterator to display the key and value System. out. println ("the value Map after \ n is:"); for (Object key: keys) {String value = map. get (key); System. out. println (key + "=" + value );}}}

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.