Considerations for using the set:
1,Objects can only be referenced in a set, and Native data types cannot be placed., We need to use native data type packaging classes to add them to the Set (jdk5 will automatically perform the packing and unpacking operations, on the surface, the collection can be directly placed in the native data type, but it is actually automatically packed into objects );
2. All objects are placed in the set. Therefore, the object type is obtained (any data type can be placed ), you must use the forced type conversion to convert it to the actual type (placed type ).
Arraylist
Common arraylist methods:
boolean add(E e)void add(int index, E element)void clear()E get(int index)int indexOf(Object o)boolean isEmpty()E remove(int index)boolean remove(Object o)int size()Object[] toArray()
Analysis of Common arraylist methods:
1. Constructor
List list = new ArrayList();
Arraylist underlying layerArray ImplementationWhen arraylist object is generated using a constructor without parameters, an array of the object type with a length of 10 is actually generated at the underlying layer to store the object (address ). For details, see the JDK source code:
public ArrayList() { this(10);}public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity];}private transient Object[] elementData;
2. Add () method
If more than 10 elements are added, the arraylist underlying layer will generate an array,The length is 1.5 times + 1 of the original array.;
Then, copy the content of the original array to the new array, and add the content to the new array. When the new array cannot accommodate the added elements, repeat the process. For details, see the JDK source code:
public boolean add(E e) { ensureCapacity(size + 1); // Increments modCount!! elementData[size++] = e; return true;}public void ensureCapacity(int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3)/2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }}public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass());}
public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++;}public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
3. Size () method
Returns the length of the list.
public int size() { return size;}private int size;
4. Remove () method
public E remove(int index) { RangeCheck(index); modCount++; E oldValue = (E) elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue;}public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
5. Summary of common arraylist methods:
1. All arraylist MethodsNone of them are synchronizedAnd VectorMost public methods are synchronized.Of;
2. For the arraylist element,To add or delete an element, you need to move it forward or backward. The cost is high.. HoweverFast search(Determined by the characteristics of the array );
3. When adding or deleting an element, the arraylist isUsing system. arraycopy () to move a large number of elementsInQuick locating by array subscript;
Shortlist
The following are common methods for listing objects:
public void addFirst(E e)public void addLast(E e)public E getFirst()public E getLast()public E peek()public E pop()E remove(int index)public void push(E e)
Frequently Used Method Analysis of the listing list:
1. Constructor
LinkedList list = new LinkedList();
Public writable list () {// during initialization, the node's precursor and subsequent directions are directed to itself (header). A loop is formed. Header. next = header. previous = header;} // define the header node of the upload list: Private transient entry <E> header = new entry <E> (null, null, null ); private transient entry <E> header = new entry <E> (null, null, null); Private Static class entry <E> {E element; Entry<E> next; entry <E>Previous;Entry (E element, entry <E> next, entry <E> previous) {This. Element = element; this. Next = next; this. Previous = previous ;}}
Element is the element we want to add to the listing list. Then, the entry constructs the previous and next references both forward and backward, and finally adds the generated entry object to the linked list;
In other words,Each entry object is maintained in the comment list..
2,Add () method
public boolean add(E e) { addBefore(e, header); return true;}private Entry<E> addBefore(E e, Entry<E> entry) { Entry<E> newEntry = new Entry<E>(e, entry, entry.previous); newEntry.previous.next = newEntry; newEntry.next.previous = newEntry; size++; modCount++; return newEntry;}
3. Remove () method
When the remove () method is called, only the objects indicated by its previous and next are changed.
public E remove(int index) { return remove(entry(index));}private E remove(Entry<E> e) { if (e == header) throw new NoSuchElementException(); E result = e.element; e.previous.next = e.next; e.next.previous = e.previous; e.next = e.previous = null; e.element = null; size--; modCount++; return result;}
Comparison between arraylist and rule list
1,Arraylist uses arrays at the underlying layer, which is essentially a variable-length array referenced by objects; List uses bidirectional linked lists at the underlying layer.;
2. When an insert or delete operation is performed (essentially determined by the characteristics of a bidirectional cyclic linked list), it is better to use the sort list;
3. When performing the search operation (which is essentially determined by the characteristics of the array), it is better to use arraylist;
Common interview questions:
Question 1: How does the size of arraylist automatically increase? Can you share your code?
When you try to add an object to the arraylist, Java will check the arraylist andMake sure that the existing array has enough capacity to store this new object.;
If there is not enough capacity, a new long array will be created, and the old array will useThe arrays. copyof method is copied to the new array.,The existing array references the new array.;
// Arraylist add method: Public Boolean add (E) {ensurecapacity (size + 1); // increment modcount !! Elementdata [size ++] = E; return true ;}// ensurecapacity method: process the size of arraylist public void ensurecapacity (INT mincapacity) {modcount ++; int oldcapacity = elementdata. length; If (mincapacity> oldcapacity) {object olddata [] = elementdata; int newcapacity = (oldcapacity * 3)/2 + 1; if (newcapacity <mincapacity) newcapacity = mincapacity; // mincapacity is usually close to size, so this is a win: elementdata = arrays. copyof (elementdata, newcapacity );}}
Pay attention to the following three points:
1) A new array is created;
2) The object of the old array is copied to the new array;
3) and the existing array points to the new array;
Question 2: under what circumstances will you use arraylist? When will you select the upload list?
In most casesWhen accessing elements more frequently than inserting or deleting elements, you should use arraylist;
On the other hand, when you are in a particular index,When you insert or delete elements more frequently, or you do not need to access the elements at all, you should select the sort list;
The main reason is:
1) the worst time complexity for accessing elements in the arraylist is "1", and it may be "n" in the list;
2) adding or deleting an element in the arraylist usually calls system. the arraycopy method is a resource-consuming operation. Therefore, when elements are inserted or deleted frequently, the performance of the sorted list is better.
Question 3: how to copy an arraylist to another arraylist? Write your code?
1)Use the clone () methodFor example, arraylist newarray = oldarray. Clone ();
2)Arraylist ConstructorFor example, arraylist myobject = new arraylist (mytempobject );
3)Use the copy method of collection.
Note that values 1 and 2 are shallow copies ).
Question 4: How does one add or delete an object in arraylist? Is efficiency low? Why?
Add or delete elements in the arraylist.Very inefficient operations such as calling system. arraycopyIf frequent insertion or deletion is required, you can select another Java set, such as the collections list.
Add an element to an index I in arraylist:
public void add(int index, E element) { if (index > size || index < 0) throw new IndexOutOfBoundsException( "Index: "+index+", Size: "+size); ensureCapacity(size+1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
Delete the element at index I of arraylist:
public E remove(int index) { RangeCheck(index); modCount++; E oldValue = (E) elementData[index]; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // Let gc do its work return oldValue; }
Question 5: What are the differences between arraylist, arraylist, and vector?
1) The underlying layer of arraylist is implemented using arrays, And the array type is object;
2) List list = new arraylist (); an array with a length of 10 is generated at the underlying layer to store objects;
3) For arraylist and vector, the underlying layer is implemented using arrays. This array is an object-type array;
4) for arraylist, the methods are not synchronized. For vector, most public methods are synchronized. (Comparison of memory stringbuffer and stringbuilder );
5) for arraylist, the search speed is very fast, and the deletion and addition operations are very slow, which is essentially determined by the characteristics of the array;
6) for the sort list, the bottom layer uses a bidirectional cyclic linked list. Searching is very slow, and adding and deleting operations are very fast, which is essentially determined by the two-way cyclic linked list;
7) arraylist is thread unsafe, but efficient; vector thread is safe, but inefficient;
Analysis of common methods in JDK sets: arraylist & Comparison List & comparison analysis of the two