Object-oriented, collection (1)

Source: Internet
Author: User

First, the concept of a collection

The collection stone contains simple objects that contain multiple objects, which are called elements . A collection can contain any number of objects, the quantity can vary, and the type of the object is not limited, that is, the type of all objects within the collection can be the same or different.

We used to store objects used by our own array of set, the length and type are single, the function is not so full. but It is important to note that the collection class holds the object's references, not the object itself.

Ii.. Data structure classification

(1) sequential storage (2) chained storage (3) tree storage (4) hash store hash (5) map map Store

The Aggregate Framework consists of a set of interfaces used to manipulate objects, without mentioning the different types of groups that the interface describes. (Is the Java Collection Framework)


The Assembly framework interface and its features:

The 1:collection interface is a set of objects that allow duplicates.

2:set interface collection, unordered but not repeatable.

The 3:list interface inherits collection, is ordered but allows repetition, and introduces positional subscripts.

The 4:map interface neither inherits the set nor inherits the collection, is a key-value pair.

These sets of framework interfaces are described in detail below

Collection interface:

Concept: The collection interface is used to represent any object or group of elements. This interface is used when you want to handle a set of elements in the usual way possible.

Iterator interface: used primarily to enumerate elements in a collection. A lookup component that can be understood as a collection. Iterators, also known as enumerators, are the enumeration of elements in a set, which is equivalent to holding a student's roster by name.

Group operations: Other operations supported by the collection interface are either tasks that act on an element group, or tasks that act on the entire collection at the same time.

Boolean contains (Object obj)----------Determine if it contains the specified element
Boolean AddAll (Collection Collection)----------Fetch and set
void Clear ()----------Remove all elements from this collection
void RemoveAll (Collection Collection)----------Remove all elements in this Collection that are also contained in the specified Collection
void Retainall (Collection Collection)----------intersection

Set interface:

Concept: By definition, the set interface inherits the collection interface, and it does not allow duplicates to exist in the collection. All the original methods are readily available in collection and no new methods are introduced.

The specific set implementation class relies on the Equals () method of the added object to check for equivalence.

HashSet class and TreeSet class:

The "Set framework" supports two common implementations of the set interface: HashSet and TreeSet. In more cases, HashSet stores the collection of repeated liberties. With efficiency in mind, objects added to the hashset need to implement the Hashcode () method in a way that distributes the hash code appropriately. The TreeSet implementation is useful when you need to extract elements in an orderly manner from the collection. To be able to proceed smoothly, the elements added to the TreeSet must be sortable.

List interface:

Concept: The list interface inherits the collection interface to define an ordered set of allowed duplicates. This interface is not only able to process a part of the list, but also adds a location-oriented operation.

Location-oriented operations include the ability to insert an element or collection, and also to get, drop, or change the functionality of an element. Searching for an element in the list starts at the head or tail of the listing, and if an element is found, it also reports where the element is located.

void Add (int index, Object Element)----------added to the specified position
Boolean addall (int index, Collection Collection)----------Add all the elements in the Collection and return the Boolean type
Object get (int index)----------Gets the element at the specified position
an int indexOf (Object Element)----------Returns the index of the specified element that first appeared in this list, or 1 if the list does not contain elements.
an int lastIndexOf (Object Element)----------Returns the index of the specified element that occurred last in this list, or 1 if the list does not contain an index
Object Remove (int index)----------Remove the element at the specified position in this list
Object Set (int index, Object Element)----------Replace the element at the specified position
List sublist (int fromIndex, int toindex)

Attention:

1) The Hashcode () method is not called automatically when a list (such as ArrayList) is used. Because in the list, repeating is repeated, do not need to judge, to ensure uniqueness.
2) The list is added the function of subscript index, so that the modification of the list can use the set method to the specified position of the element directly replaced, do not need to be as complex as set (to convert the array to modify, and then to convert back).
3) collection with the iterator iterator, and list can be used with the Listiterator listing iterator. The former can only be next (), which contains not only the next () method, but also the previous () method. Therefore, if you want to use the list to do similar to the book page, you can not only flip backwards, but also forward.

There are two general list implementations in the collection framework: ArrayList and LinkedList. If you want to support random access without having to insert or drop elements at any point except the trailer, ArrayList provides an optional collection. However, if you want to add and remove elements frequently from the middle of the list, and as long as the sequential access list element, then the LinkedList implementation is better. 、

The following uses ArrayList to implement queues and stacks:

Queue Implementation code:

Import java.util.arraylist;import java.util.list;/* * Use ArrayList collection to implement queue in queue, out queue, whether empty operation */public class Myque {private List<object> list =new arraylist<object> (); Defines an ArrayList set int index=0; The queue pointer, pointing to the last element public void in (Object obj) {//Incoming queue List.add (index, obj);//each time it is added at the end of the queue index++;} public object Out () {//Outbound queue Object obj=list.remove (0);//Take the first element from the collection pops Index--;return obj;} public Boolean isEmpty () {//Determines whether the queue is empty return list.isempty ();//directly determines whether the collection is empty}}

Stack implementation code:

Import java.util.arraylist;import java.util.list;/* * Use ArrayList collection to implement the stack, the stack operation. */public class Mystack {private list<object> list=new arraylist<object> (0);//define a ArrayList collection private int The index=0;//stack pointer, which points to the last element of the stack, public void push (Object obj) {//Stack list.add (index,obj);//Add the elements that need to be stacked to the list index++;} Public Object Pop () {//out stack index--;object obj=list.get (index),//Popup element List.remove (index),//Remove bounce element return obj;}}

ArrayList Code Demo:

Import Java.util.arraylist;import Java.util.list;public class Arraylistdemo {public static void main (string[] args) { List<student> list =new arraylist<student> (); Create the ArrayList interface//new element object, here is the Student object Student s1=new Student ("1001", "Zhou", ();    Student s2=new Student ("1002", "Zhou", 57); Student s3=new Student ("1003", "Zhou", 57); Student s4=new Student ("1004", "Zhou", 97);//Add the above object to list List.add (S1); List.add (S2); List.add (S3); List.add (S4);// Output object for (int i=0;i<list.size (); i++) {Student s=list.get (i); System.out.println (s);}}}

Results:

LinkedList Code Demo:

Import Java.util.linkedlist;public class Linkedlistdemo {public static void main (string[] args) {Linkedlist<object > List=new linkedlist<object> (); Create the LinkedList interface//new element Object, here is the Student object Student s1=new Student ("1001", "Zhou", 67); Student s2=new Student ("1002", "Zhou", 57); Student s3=new Student ("1003", "Zhou", 57); Student s4=new Student ("1004", "Zhou", 97);//Add the above object to list List.add (S1); List.add (S2); List.add (S3); List.add (S4); List.add ("ABCD"); List.add (100);//Add AAA to the first position in the list List.addfirst ("AAA");//Remove the element with position ordinal 3 list.remove (3);// Modify the element with position ordinal 2 to 88list.set (2, 88);//output for (int i=0;i<list.size (); i++) {Object obj=list.get (i); System.out.println (obj);} Outputs the first element of System.out.println (List.getfirst ());}}

Results:


Student object code:

public class Student {private String sno, Sname;private int score;//constructor Public Student (String sno, string sname, int score {This.sno = Sno;this.sname = Sname;this.score = score;} The following is the GET, set function public String Getsno () {return sno of the corresponding parameter;} public void Setsno (String sno) {This.sno = sno;} Public String Getsname () {return sname;} public void Setsname (String sname) {this.sname = sname;} public int Getscore () {return score;} public void SetScore (int score) {This.score = score;} ToString function @overridepublic String tostring () {return "Student [sno=" + Sno + ", sname=" + sname + ", score=" + score+ "]" ;}}



Map interface:

Concept: The map interface is not an inheritance of the collection interface. Instead, start with your own interface hierarchy for maintaining key-value associations. By definition, this interface describes a key-to-value mapping that is never duplicated.

Object put (object Key,object value)---------New or modified
Object remove (object key)---------modified by key
void Putall (Map mapping)----------add elements from a map
void Clear ()----------remove all elements from the list
Object get (Object key)----------through the value of the key value or

Map.entry interface: Map's EntrySet () method returns an object set set that implements the Map.entry interface, where each object is a specific key-value pair in the underlying map.


HashMap class and TreeMap class: (All implemented Cloneable interface)

The "collection Framework" provides two general map implementations: HashMap and TreeMap. HashMap is the best choice for inserting, deleting, and locating elements in a map. But if you want to traverse the keys sequentially, then TreeMap is better.

The key class that is added with HashMap requires a clear definition of the hashcode () implementation (understanding: Map.keyset Returns the set set of keys, and the set set has a limit on the hashcode implementation, so the class that is the key is also subject to that restriction). With the TreeMap implementation, the elements added to the map must be sortable.


HashMap Code Demo:

Import Java.util.collection;import java.util.hashmap;import Java.util.iterator;import Java.util.Map;import Java.util.map.entry;import Java.util.set;public class Hashmapdemo {public static void main (string[] args) {HashMap Map = n  EW HashMap (); Create HashMap interface//Add Map.put ("1001", "Zhang June"), Map.put ("1002", "Zhang Sa"), Map.put ("1003", "Wang June"), Map.put ("1014", "Liu Sheng"), Map.put ("     1015 "," Zhang San ");//delete Map.Remove (" 1001 ");//Modify Map.put (" 1003 "," Mary ");//Lookup//Traversal Method 1: Through key view set keys = Map.keyset ();  Returns a Set view of the keys contained in this map iterator it = keys.iterator (); Use an iterator to read data//read data from an iterator while (It.hasnext ()) {String key = (string) it.next (); String values = (string) map.get (key); Obtain the corresponding value value by the key value System.out.println (key + "," + values); Output}//Traversal Method 2: Through Entry view System.out.println ("-----------------------------");     Set Entries=map.entryset (); Returns a Set view of the mappings contained by this map.  Iterator It2=entries.iterator (); Use iterators to read data while (It2.hasnext ()) {map.entry entry= (Entry) it2.next (); String key = (string) entry.getkey (); String values= (String) map.get(key); System.out.println (key+ "," +values);} Traversal Method 3: Through the value view, this cannot output key value System.out.println ("---------------------");  Collection values=map.values ();  Returns a Collection view of the values contained by this map iterator it3=values.iterator (); Use an iterator to read the data while (It3.hasnext ()) {string value= (String) it3.next (); System.out.println (value);}}}

Results:

TreeMap Code Demo:

Import Java.util.iterator;import java.util.map;import Java.util.map.entry;import Java.util.set;import Java.util.treemap;public class Treemapdemo {public static void main (string[] args) {TreeMap map=new TreeMap (); Map.put (" 1001 "," Zhang June "); Map.put (" 1002 "," Zhang Sa "), Map.put (" 1003 "," Wang June "), Map.put (" 1014 "," Liu Sheng "), Map.put (" 1015 "," Zhang San ");// Traversal: Set Entries=map.entryset () via entry view;  Returns the Set view of the mappings contained in this map iterator it=entries.iterator (); while (It.hasnext ()) {map.entry entry= (Entry) it.next (); String key= (String) Entry.getkey (); String value= (String) entry.getvalue (); System.out.println (key+ "," +value);}}}

Results:


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Object-oriented, collection (1)

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.