"Javase" Day05_list Collection _list Sort _ queue and stack

Source: Internet
Author: User
Tags comparable rand

"Javase" Day05_list Collection _list Sort _ queue and stack


1.List Collection

1) ordered set, repeatable set. The list is characterized by the ability to manipulate elements as an array, depending on the subscript. So list offers some unique methods.

2) Common Implementation classes:

--arraylist: Internal array implementation, query fast.

--linkedlist: Internal chain list implementation, and delete quickly.

3) E get (int index)

Gets the element that corresponds to the specified subscript. (Subscript starting from 0)

4) e set (int index,e e)

Sets the given element to the specified position, returning the value to the element at the original position. So the action is to replace the element operation.

Note: You need to operate on an existing element.

Code Demo:


Package Day04;import java.util.arraylist;import Java.util.iterator;import java.util.list;/** * List Collection * Ordered set, repeatable set. * list is characterized by the ability to manipulate elements like arrays, according to subscript. * So list offers some unique methods. * Common Implementation class: * ArrayList: Internally by the array implementation, query fast. * LinkedList: Internal chain list implementation, and delete quickly. * */public class ListDemo01 {public static void main (string[] args) {list<string> List = new arraylist<string> List.add ("one"), List.add ("one"), List.add ("three"), List.add ("four"),/* * E get (int index) * Gets the element that specifies the subscript. (Subscript starting from 0) */string str = list.get (0); System.out.println (str); one//traverses all elements//1.for (int i=0;i<list.size (); i++) {//size () to get the number of container elements str = list.get (i); System.out.println (str);} 2.iterator<string> it = List.iterator (); while (It.hasnext ()) {str = It.next (); System.out.print (str+ "");} System.out.println ();/* * E set (int index,e E) * Sets the given element to the specified position and returns the element on the original position *. So the action is to replace the element operation. * Note: You need to operate on an existing element. *///[one,2,three,four]string old = List.set (1, "2"); SYSTEM.OUT.PRINTLN (list); System.out.println ("The replaced element is:" +old); List.add (2, "# # #"); List.add (5, "1"); System.oUT.PRINTLN (list);}} 

5) void Add (int index,e E)

Inserts the given element at the specified position, moving backward in the original position and subsequent element order.

6) E Remove (int index)

Deletes and returns the element at the given position.

Code Demo:


Package Day04;import Java.util.linkedlist;import java.util.list;/** * List provides another pair of methods: * void Add (int index,e E) * Inserts a given element into the specified position The original position and subsequent elements are moved backwards. *  * E Remove (int index) * Deletes and returns the element at the given position. * */public class ListDemo02 {public static void main (string[] args) {list<string> List = new Linkedlist<string> ;(), List.add ("one"), List.add ("one"), List.add ("three"), List.add ("four"); SYSTEM.OUT.PRINTLN (list); [One, three, Four]//[one, 3, Three, Four]list.add (2, "3"); SYSTEM.OUT.PRINTLN (list); [One, two, 3, three, Four//[one, two, 3, three, four, 5]//append a list.add at the end (5, "5"); SYSTEM.OUT.PRINTLN (list); [One, 3, three, four, 5]//[one, A, 3, four, 5]string old = List.remove (3); Subscript cannot cross System.out.println (list); [One, 3, four, 5]system.out.println ("The deleted element is:" +old); ThreeSystem.out.println (List.get (3));}}

7) List sublist (int start,int end)

Gets a partial subset of a given range within the current collection

Any operation on a subset affects the original collection.

Clears the subset, and the contents of that part of the original collection are also deleted. Quickly delete the specified contents of the original collection by emptying the subset.

Code Demo:


Package Day04;import Java.util.arraylist;import java.util.list;/** * Get a subset of the list collection * */public class ListDemo03 {public STA tic void Main (string[] args) {list<integer> List = new arraylist<integer> (); for (int i=0;i<10;i++) { List.add (i);} SYSTEM.OUT.PRINTLN (list); [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]/* * List sublist (int start,int end) * Gets a subset of the subsets within a given range in the current collection */list<integer> sublist = l Ist.sublist (3,8); System.out.println (sublist); [3, 4, 5, 6, 7]//expands each element of the sub-set by 10 times times for (int i=0;i<sublist.size (); i++) {/*int n = sublist.get (i); n = n*10;sublist.set (i,n) ; */sublist.set (I,sublist.get (i) *10);} System.out.println (sublist); [30, 40, 50, 60, 70]/* * Any operation on a subset will affect the original collection. */SYSTEM.OUT.PRINTLN (list); [0, 1, 2, 30, 40, 50, 60, 70, 8, 9]//empties the subset, and the contents of that part of the original collection are also deleted. Quickly delete the specified contents of the original collection by emptying the subset. Sublist.clear (); SYSTEM.OUT.PRINTLN (list); [0, 1, 2, 8, 9]}}

8) Set Conversion array

A method toarray is provided in collection that allows us to convert an existing collection into an array.

Code Demo:


Package Day04;import java.util.arraylist;import Java.util.arrays;import java.util.collection;/** * Collection Conversion array * Collection provides a method ToArray * allows us to convert an existing collection into an array. * */public class Colletiontoarray {public static void main (string[] args) {collection<string> C = new Arraylist<s Tring> (), C.add ("one"), C.add ("one"), C.add ("three"), C.add ("four"); string[] Array = C.toarray (new String[c.size ())); System.out.println (arrays.tostring (array)); [One, the other, three, four]array[0]= "1"; System.out.println (arrays.tostring (array)); [1, three, four]system.out.println (c); [One, the other, three, Four]c.add ("# #"); System.out.println (arrays.tostring (array)); [1, three, four]system.out.println (c); [One, two, three, four, ##]/* * Summary: When the set is converted to an array, the elements in the collection can be modified and checked, and the operation is not affected. * When an object is stored in the collection, changes are followed when the value of the property in the object is changed. */}}

9) arrays are converted into collections

static methods using arrays Aslist () need to be aware that arrays can only be converted to a list collection and cannot be converted to set. Reason:

* 1.Set is mostly unordered

* 2.Set is not allowed to hold duplicate elements, so the element may be lost after conversion.

For collections that are converted by arrays, adding elements is not supported!

Code Demo:

Package Day04;import Java.util.arraylist;import Java.util.arrays;import java.util.list;/** * Arrays converted to Collections * static methods using Arrays Aslist () * Note that arrays can only be converted to a list collection and cannot be converted to set. * Reason: * 1.Set is mostly out of order implementation * 2.Set does not allow repeating elements, so the conversion may be missing elements. * */public class Arraytolist {public static void main (string[] args) {string[] array = new string[]{"One", "I", "three"};l ist<string> list = arrays.aslist (array); SYSTEM.OUT.PRINTLN (list); [One, three]/* * modifies the contents of the collection element, the contents of the original array will also change */list.set (0, "1"); SYSTEM.OUT.PRINTLN (list); [1, two, three]//array the first element also becomes "1" System.out.println (arrays.tostring (array)); [1, three]array[2] = "222"; SYSTEM.OUT.PRINTLN (list); [1, 222]system.out.println (arrays.tostring (array)); [1, 222]/* * For collections that are converted by arrays, adding elements is not supported! * So the code below will throw an exception. * Java.lang.UnsupportedOperationException *///list.add ("four");//system.out.println (list); Error */* array---Set Summary: * 1. You can only modify the collection elements, cannot delete and add * 2. When modifying an array or an element in a collection, it affects the other. * 3. If you want to make additions or deletions to the collection, you can new a collection. *//* * All collections support One constructor method, and parameters require passing in another collection. * The function of this constructor is: * Create the current collectionAdds all the elements in the given collection to the current collection at the same time. * Any operation of the new collection after creation is independent of the original collection. No effect on the original set. */list<string> List1 = new arraylist<string> (List); Copy//list1.addall (list), List1.add ("1"), List1.set ("# #"); System.out.println (List1); SYSTEM.OUT.PRINTLN (list);}}

2.List Sorting

1) collectioNS: Set of Tool classes

This class provides a number of static methods that allow you to manipulate collections conveniently. Where the sort method is used to sort the list set. Make a natural sort (small to large).

Code:


Package Day05;import Java.util.arraylist;import Java.util.collections;import java.util.list;import java.util.Random ;/** * Collections: A collection of tool classes * This class provides several static methods that allow you to manipulate the collection conveniently. * Where the Sort method is used to sort the list set. Make a natural sort (from small to Large) * */public class SortDemo01 {public static void main (string[] args) {list<integer> List = new ArrayList <Integer> (); Random rand = new Random (); for (int i=0;i<10;i++) {list.add (Rand.nextint (100));} SYSTEM.OUT.PRINTLN (list);/* Sort will naturally sort the elements in a given list collection * that is: from small to large order *  * Interview: * Collection and collections difference? (or say them separately) *  *  */collections.sort (list); SYSTEM.OUT.PRINTLN (list);}}

2) Comparable interface

2.1) Collections The sort method if you want to sort the collection, you must ensure that the elements in the collection are comparable in size.

Therefore, the requirement element must implement the comparable interface and override the comparison size method (CompareTo ) in order to sort.

2.2) The function of the CompareTo method is to make the current object compare to the given object o size. The return value does not focus on the specific value, but instead focuses on the range of values:
* When return value >0: The current object is larger than the parameter object

* When return value <0: The current object is smaller than the Parameter object

* When return value = 0: Two objects are equal

2.3) The current element if you want to compare the size, you need to implement the comparable interface, comparable support generics, and the actual type of generics is the current class. This means that the class implements the comparable interface, which is the generic type.

Code Demo:


Package Day05;import Java.util.arraylist;import Java.util.collections;import java.util.list;import java.util.Random ;p Ublic class SortDemo02 {public static void main (string[] args) {list<point> List = new arraylist<point> ();// Random rand = new Random (),//for (int i=0;i<5;i++) {//list.add (new Point (Rand.nextint), Rand.nextint (10)), or/} List.add (new Point), List.add (new Point (7,9)), List.add (new Point (5,4)); SYSTEM.OUT.PRINTLN (list); (7,9), (5,4)]/* * Collections The Sort method if you want to sort the collection, you must ensure that the elements in the set * are comparable in size. * So the requirement element must implement the comparable interface and override the * comparison size method in order to sort. */collections.sort (list); SYSTEM.OUT.PRINTLN (list); (5,4), (7,9)]/* * Although the sort method can naturally sort the elements in the collection * but must require the element to implement the comparable interface, this occurs * because you want to use the sort function and must change the * content of our defined classes, this phenomenon is called " Invasive ". */}}

3) Collections The overloaded Sort method:

Ask us to pass in two parameters: 1: Set to be sorted 2: Comparator

3.1) There are usually two cases in which the collection is sorted using this method:

* 1: The element has implemented the comparable interface, but the size of the rule does not meet our need for sorting.

* 2: The element does not implement the comparable interface, and it does not want to force the modification of the element for ordering here, requiring it to implement the interface.

3.2) Anonymous inner class implementation comparator interface

Code Demo:

Package Day05;import Java.util.arraylist;import Java.util.collections;import java.util.comparator;import java.util.list;/** * Collections Overloaded Sort method * */public class SortDemo03 {public static void main (string[] args) {/* * string str ING implements the comparable interface * collation: According to the first letter of the encoding ratio size. */list<string> List = new arraylist<string> (); List.add ("old"); List.add ("Mr Ozawa"); List.add ("Teacher Fan"); List.add ("Little Teacher"); SYSTEM.OUT.PRINTLN (list); [Old, Mr Ozawa, teacher fan, little teacher]/* * Collections's overloaded Sort method requires us to pass in two parameters: * 1: The set to be sorted * 2: Comparator * * There are usually two cases in which the method is used to sort the collection: * 1: The element has been implemented Comparab Le interface, but the comparison size of the * rule does not meet our need for sorting. * 2: The element does not implement the comparable interface, and it does not want to force the modification of the element in order to be sorted here, requiring it to implement the interface. * *///external class implementation Comparator interface//mycomparator COM = new Mycomparator ();//collections.sort (list,com);// The anonymous inner class implements the Comparator interface Collections.sort (list,new comparator<string> () {@Overridepublic int compare (String O1, String O2) {return o1.length ()-o2.length ();}); *comparator<string> comp = new comparator<string> () {@Overridepublic int compare (String O1, StrinG O2) {return 0;}}; *///Anonymous internal class SYSTEM.OUT.PRINTLN (list); [Old, teacher fan, Xiao Teacher, ozawa teacher]}}class Mycomparator implements comparator<string>{@Overridepublic int compare (String O1, String O2) {return o1.length ()-o2.length ();}}

3. Queues and Stacks

1) Queuing (queue)

Save a set of elements, but for access requirements, you must follow the FIFO principle.

1.1) Boolean offer (E e)

Appends an element to the end of a queue

1.2) E poll ()

Gets the element from the first team. Notice that the element is removed from the queue after getting the class! Out of the team operation.

1.3) E Peek ()

You can also get the first element of the team, but unlike poll, the element is not removed from the queue.

See the code for details:

Package Day05;import java.util.linkedlist;import java.util.queue;/** * Queue * Saves a set of elements, but must follow the * FIFO principle * * */public C for access requirements Lass Queuedemo {public static void main (string[] args) {queue<string> Queue = new linkedlist<string> ();/* * bo Olean offer (e e) * Append an element */queue.offer ("one") to the end of the queue, Queue.offer ("two"), Queue.offer ("three"), Queue.offer ("four"); System.out.println (queue); [One, three, four]/* * E poll () * Gets the element from the first team. Notice that the element is removed from the queue * after getting the class! Out of the team operation */string str = Queue.poll (); System.out.println (str); OneSystem.out.println (queue); [Three, four]/* * E peek () * can also get the first element of the team, but unlike poll, the element will not be removed from the queue. */str = Queue.peek (); System.out.println (str); TwoSystem.out.println (queue); [Three, four]//queue traversal//1.for (int i=0;i<queue.size (); i++) {String str1 = Queue.poll (); System.out.println (STR1);} Cause: Each time A For loop is executed, queue.size () will lose one System.out.println (queue); [four]//1.2 Improvement--inverted for (int i=queue.size (); i>0;i--) {String str1 = Queue.poll (); System.out.println (STR1);} System.out.println (queue); []//2.--while Loop--Recommended while (Queue.size () >0) {String str1 = Queue.poll (); System.out.println (STR1);} System.out.println (queue); //[]}}

2) stack (stack)

To store a set of elements, access must follow the advanced post-out principle.

2.1) Deque (double-ended queue) is a sub-interface of the queue.

The characteristics of a double-ended queue: Both ends of the queue can be in and out of elements. If we only invoke one side of the access method, the stack structure is formed.

2.2) void push (E e)

The element is "pushed into" the stack, and the stack is put into action. The elements of the new stack are at the top of the stack (the first element in the stack).

2.3) E pop ()

The stack operation gets the top element of the stack, and the element is removed from the stack after getting it.

2.4) You can also use Peek () to refer to the top element of the stack without making a stack operation.

Code Demo:

Package Day05;import java.util.deque;import java.util.linkedlist;/** * Stack: Stores a set of elements, access must follow the advanced post-out principle. * Usually used to achieve a "back" function of the place. * */public class Stackdemo {public static void main (string[] args) {/* * deque is a sub-interface of the queue. * Features of the double-ended queue: Both ends of the queue can be in and out of elements. * If we only invoke one side of the access method, it forms a stack structure. * */deque<string> stack = new linkedlist<string> ();/* void push (e e) * elements are "pressed" into the stack. * The new stack element will be at the top of the stack (the first element in the stack). */stack.push ("one"), Stack.push ("one"), Stack.push ("three"); SYSTEM.OUT.PRINTLN (stack); [Three, One]//stack.offerlast ("#"),//system.out.println (Stack),/* * E pop () * Out of the stack operation, get the top element of the stack, obtained after the element is deleted from the stack. */string str = Stack.pop (); System.out.println (str); THREESYSTEM.OUT.PRINTLN (stack); [Both, one]/* * can also use peek () to refer to the top element of the stack, * without making a stack operation. */str = Stack.peek (); System.out.println (str); TWOSYSTEM.OUT.PRINTLN (stack); [Both, one]/* * traversal, and queue same */while (Stack.size () >0) {System.out.println (Stack.pop ());} SYSTEM.OUT.PRINTLN (stack); []//system.out.println (Stack.poll ());//system.out.println (Stack.poll ());}}

Note: The LinkedList implements the List<e> Deque<e> interface





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

"Javase" Day05_list Collection _list Sort _ queue and stack

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.