What is the difference between ArrayList and LinkedList? An example illustrates the functionality that LinkedList can implement.

Source: Internet
Author: User


For processing a list of data items, Java provides two classes ArrayList and linkedlist,arraylist internal implementations are based on an internal array object[], so conceptually, it's more like an array, But LinkedList's internal implementation is based on a set of connected records, so it's more like a list structure, so there's a big difference in performance.
When inserting data in front or in the middle of a ArrayList, all subsequent data must be moved backwards so that it takes more time, so when your operation is to add data after a column of data rather than in front or in the middle, and you need to randomly access its elements, The use of ArrayList will provide better performance;
When you access an element in a linked list, you have to look at one end of the list to find the element along the direction of the connection, until you find the elements you want, so when you are adding or deleting data in front or in the middle of a column of data, and accessing the elements in the order, You should use the LinkedList.
If in the programming, two kinds of situations alternately appear, at this time, may consider uses the list such universal interface, but does not care about the concrete implementation, in the concrete case, its performance is guaranteed by the concrete realization.
Case: LinkedList Implementation Stack
Case description
ArrayList query efficiency is relatively high, adding or deleting the efficiency of the action is poor, suitable for the query more frequent, and additions and deletions less action element management collection. LinkedList query efficiency is low, but the deletion efficiency is very high. Applicable to additions and deletions of the more frequent, less than the number of queries to manage the collection of elements.
Arraylist,linkedlist are thread-unsafe.
Implementation stack 1) array (ArrayList, adding and removing efficiency is lower, not suitable)
2) LinkedList (a good way to implement the stack)
3 Java.util.Stack class, Stack is a vector subclass, vector class is a thread-safe (is a heavyweight class), and inherits the Vector method, the Verctor class and ArrayList functions are almost the same. (Stack classes are not recommended to implement stacks).
Implementation process
Import java.util.*;
public class Teststack {
public static void Main (string[] args) {
Mystack ms=new mystack ();
Ms.push ("Chenzq");
Ms.push ("Liucy");
Ms.push ("Bailu");
System.out.println (Ms.pop ());
System.out.println (Ms.pop ());
System.out.println (Ms.pop ());
}
}
Class mystack{
Private LinkedList ll=new LinkedList ();
public void push (Object o) {
Ll.addfirst (o);
}
Public Object pop () {
return Ll.removefirst ();
}
}
32. What is the concept of threads. How threads communicate with each other.

A thread is an execution unit in a process, and each thread in the same process corresponds to a set of CPU instructions, a set of CPU registers, and a stack. Process has a dynamic meaning, but in essence, through the implementation of the thread, in this sense, the dynamic meaning of the process in Windows is not very obvious, only to the program accounted for a range of resources, the real dynamic meaning of the thread.
In fact, Java provides 3 very important ways to skillfully solve the problem of communication between threads. These 3 methods are: Wait (), notify (), and Notifyall (). They are the final method of the object class, so each class has them by default.
Although all classes default to owning these 3 methods, they are only practical if they are in the scope of synchronized keyword action and are used in conjunction with the 3 methods in the same synchronization problem.
The syntax formats that these methods declare in the object class are as follows:
final void Wait () throws interruptedexceptionfinal void Notify () final void Notifyall ()
where the Wait () method is invoked enables the thread that calls the method to release the lock of the shared resource, and then exits from the run state and into the waiting queue until it is awakened again. The call to the Notify () method wakes the first thread waiting in the queue to wait for the same shared resource, and causes the thread to exit the wait queue and enter the runtime state. Calling the Notifyall () method causes all threads waiting in the queue to wait for the same shared resource to exit from the wait state and into the operational state, at which point the highest priority thread executes first. Obviously, using these methods eliminates the need to cycle through the state of shared resources, but directly wakes up threads in the waiting queue when needed. This will not only save valuable CPU resources, but also improve the efficiency of the program.
Because the wait () method is declared to throw a Interruptedexception exception when it is declared, you need to place it in a Try...catch code block when you invoke the Wait () method. In addition, you need to place it in a synchronized code snippet when you use this method, otherwise the following exception occurs:
"Java.lang.IllegalMonitorStateException:current Thread not owner"
Is it possible for these methods to communicate between threads? The following is a multithreaded synchronization model: producer and consumer issues to illustrate how to solve the communication problem between multithreading through programs.
Case: Communication of threads
Case description
The following program demonstrates the specific implementation of communication between multiple threads. The program uses 4 classes, where the Sharedata class is used to define shared data and synchronization methods. The wait () method and the Notify () method are invoked in the synchronization method, and a semaphore is used to implement message passing between threads.
Implementation process
Communicationdemo.java Description: The message passing process between producer and consumer
Class Sharedata
{
private char C;
Private Boolean isproduced = false; Signal Volume
Public synchronized void Putsharechar (char c)//Sync Method Putsharechar ()
{
if (isproduced)//If the product is not yet consumed, the producer waits
{
Try{wait (); Producer Waiting
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
THIS.C = C;
isproduced = true; Mark already produced
Notify (); Inform consumers that they have produced and can consume
}
Public synchronized char Getsharechar ()//Sync Method Getsharechar ()
{
if (!isproduced)//If the product is not yet produced, the consumer waits
{
Try
{
Wait (); Consumers wait
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
isproduced = false; Mark has been consumed
Notify (); Notifications require production
return THIS.C;
}
}
Class Producer extends thread//producer Threads
{
Private Sharedata S;
Producer (Sharedata s)
{
THIS.S = s;
}
public void Run ()
{
for (char ch = ' A '; Ch <= ' D '; ch++)
{
Try
{
Thread.Sleep ((int) (Math.random () *3000));
}catch (Interruptedexception e) {
E.printstacktrace ();
}
S.putsharechar (CH); Put the product into the warehouse
SYSTEM.OUT.PRINTLN (ch + "is produced by Producer.");
}
}
}
Class Consumer extends thread//consumer threads
{
Private Sharedata S;
Consumer (Sharedata s)
{
THIS.S = s;
}
public void Run ()
{
Char ch;
do{
Try
{
Thread.Sleep ((int) (Math.random () *3000));
}catch (Interruptedexception e) {
E.printstacktrace ();
}
ch = S.getsharechar (); Remove the product from the warehouse
SYSTEM.OUT.PRINTLN (ch + "is consumed by Consumer.");
}while (ch!= ' D ');
}
}
Class Communicationdemo
{
public static void Main (string[] args)
{
Sharedata s = new Sharedata ();
New Consumer (s). Start ();
New Producer (s). Start ();
}
}

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.