aggregate ( Two )
About set elements remove
During iteration , Elements cannot be deleted directly through collection , To delete elements through iterators
package se3.collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTest06 {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add(1);
c.add(2);
c.add(3);
Iterator it = c.iterator();
while (it.hasNext()){
// When writing code next() Method return value type must be Object
Object obj = it.next();
//c2.remove();// Delete elements directly through the collection , There is no notification iterator , Will report a mistake
// Use iterators to delete
it.remove();// It must be the current element that the iterator points to
System.out.println(obj);
}
System.out.println(c.size());//0
}
}
List Interface specific methods
test List Common methods in interface
-
List Collection storage element characteristics : Orderly and repeatable
Orderly :List The elements in the set have subscripts , from 0 Start , With 1 Increasing
repeatable : Store a 1, It can also be stored in 1
-
List Since it is Collection The child interface of the interface , So sure List The interface has its own “ features ” Methods :
Only... Are listed below List Common methods of interface
void add(int index,Object element)
Object get(int index)
int indexOf(Object o)
int lastIndexOf(Object o)
Object remove(int index)
Object set(int index,Object element)
package se3.list;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ListTest01 {
public static void main(String[] args) {
// establish List A collection of types
List myList = new ArrayList();
//List myList = new LinkedList();
// Additive elements
myList.add("A");// By default, all elements are added to the end of the collection
myList.add("B");
myList.add("C");
myList.add("C");
myList.add("D");
// Add the specified element in the specified position ( The first parameter is the subscript )
// Not much , Yes ArrayList The efficiency is relatively low
myList.add(1,"KING");
// iteration
Iterator it = myList.iterator();
while (it.hasNext()){
Object obj = it.next();
System.out.print(obj + " ");
}
// Running results :A KING B C D
System.out.println();
// Get elements according to subscripts
Object obj1 = myList.get(0);
System.out.println(obj1);//A
// Because there are subscripts , therefore list The collection has its own special traversal way
// Traverse by subscript (List A unique way to assemble ,Set No, )
for (int i = 0; i < myList.size(); i++) {
Object object = myList.get(i);
System.out.print(object + " ");
}// Running results :A KING B C D
System.out.println();
// Gets the index at the first occurrence of the specified object
System.out.println(myList.indexOf("KING"));//1
// Gets the index at the last occurrence of the specified object
System.out.println(myList.lastIndexOf("C"));//4
// Delete the element with the specified subscript
// Delete the subscript as 0 The elements of
myList.remove(0);
System.out.println(myList.size());//5
// Modify the element at the specified location
myList.set(2,"Soft");
// Traverse
for (int i = 0; i < myList.size(); i++) {
Object object = myList.get(i);
System.out.print(object + " ");
}
// Running results :KING B Soft C D
}
}
ArrayList aggregate
ArrayList Set initialization capacity and expansion
1. The default initialization capacity is 10( The bottom layer first creates a length of 0 Array of , When you add the first element , The initialization capacity is 10)
2. At the bottom of the set is a Object[] Array
3. ArrayList Aggregate expansion
Of original capacity 1.5 times
ArrayList At the bottom of the set is an array , How to optimize the ?
As little expansion as possible , Because the efficiency of array expansion is low , It is recommended to use ArrayList The number of elements is estimated before the collection , Given an initial capacity .
4. Array advantages : High retrieval efficiency
5. Array disadvantages : The efficiency of random addition and deletion of elements is low , And arrays can't store large amounts of data ( It's hard to find a large, continuous storage space )
6. Add element to end of array , It's very efficient , Unaffected
7. interview : In so many collections , Which set do you use the most ?
answer :ArrayList aggregate , Because adding elements to the end of the array is not affected by efficiency , in addition , We search for / There are many operations to find an element .
8.ArrayList Collection is not thread safe
package se3.list;
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest01 {
public static void main(String[] args) {
// The default initialization capacity is 10
List list1 = new ArrayList<>();
System.out.println(list1.size());//0
// Specify initialization capacity :20( The length of the array is 20)
List list2 = new ArrayList(20);
// A collection of size() The method is to get the number of elements in the current collection , It's not getting the capacity of the collection
System.out.println(list2.size());//0
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
list1.add(6);
list1.add(7);
list1.add(8);
list1.add(9);
list1.add(10);
System.out.println(list1.size());
// Add another element
list1.add(11);
// Here the capacity is expanded to the original 1.5 times ( Automatic expansion )
System.out.println(list1.size());//11
}
}
Construction method
- new ArrayList();
- new ArrayList(20);
package se3.list;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
// aggregate ArrayList Construction method of
public class ArrayListTest02 {
public static void main(String[] args) {
// Default initialization capacity 10
List myList1 = new ArrayList();
// Specify initialization capacity 100
List myList2 = new ArrayList(100);
// Create a HashSet aggregate
Collection c = new HashSet();
// Add elements to Set aggregate
c.add(100);
c.add(200);
c.add(900);
c.add(50);
// Through this construction method, we can make HashSet Set to List aggregate
List myList3 = new ArrayList(c);
for (int i = 0; i < myList3.size(); i++) {
System.out.println(myList3.get(i));
}
/* Running results :
50
100
900
200
*/
}
}
One way linked list data structure
For linked list data structures : The basic unit is the node Node
For a one-way linked list , Any node Node There are two properties in :
- Stored data
- The memory address of the next node
One way linked list diagram
Add element diagram
Delete the element diagram
The advantages and disadvantages of linked list
- advantage : The efficiency of random addition and deletion of elements is high .( Because adding and deleting elements does not involve a large number of element displacements ). If you encounter more business in random add and delete elements in the collection , It is recommended to use LinkedList.
- shortcoming : Query efficiency is low , Every time you look for an element, you need to traverse from the node down .
ArrayList: Bring the retrieval to the extreme
LinkedList: Take random additions and deletions to the extreme
package se3.list;
import java.util.LinkedList;
import java.util.List;
public class LinkedListTest01 {
public static void main(String[] args) {
/**
* LinkedList There are subscripts at the bottom of the set
* Be careful :ArrayList The reason is that the retrieval efficiency is relatively high , Not just because of subscripts . Because of the role of the underlying array .
* LinkedList The set still has subscripts , But search for / It's inefficient to find an element , Because only one traversal can be done from the node to the other .
*/
List list = new LinkedList();
list.add("a");
list.add("b");
list.add("c");
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
System.out.print(obj + " ");
}
// Output results :a b c
}
}
Double linked list and LinkedList aggregate
The basic unit of the bidirectional list is still a node Node
Two way linked list structure
package se3.list;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LinkedListTest01 {
public static void main(String[] args) {
/**
* LinkedList There are subscripts at the bottom of the set
* Be careful :ArrayList The reason is that the retrieval efficiency is relatively high , Not just because of subscripts . Because of the role of the underlying array .
* LinkedList The set still has subscripts , But search for / It's inefficient to find an element , Because only one traversal can be done from the node to the other .
*/
List list = new LinkedList();
list.add("a");
list.add("b");
list.add("c");
for (int i = 0; i < list.size(); i++) {
Object obj = list.get(i);
System.out.print(obj + " ");
}
// Output results :a b c
/**
* LinkedList Does the collection have initialization capacity ? No,
* Whether it's LinkedList still ArrayList, You don't need to care about which set is it in the future
* Because we're going to be interface oriented programming , The methods that are called are methods in the interface
*/
System.out.println();
List list2 = new ArrayList();// This means that the underlying layer uses an array
//List list2 = new LinkedList();// This means that the underlying layer uses a two-way list
list2.add("123");
list2.add("456");
list2.add("789");
for (int i = 0; i < list2.size(); i++) {
System.out.print(list2.get(i) + " ");
}
// Output results :123 456 789
}
}
Vector aggregate
package se3.list;
import java.util.*;
/**Vector
* 1. The bottom layer is also an array
* 2. Initialize capacity :10
* 3. How to expand the capacity of ?
* Vector The characteristics of set expansion :10-->20-->40-->80
* After the expansion, it will be the original capacity 2 times
* 4.ArrayList Collection expansion features :10-->15-->15*1.5
* ArrayList Expansion is the original capacity 1.5 times
* 5.Vector All methods in are thread synchronized , All carry synchronized keyword
* It's thread safe . Low efficiency , Less used .
*/
public class VectorTest {
public static void main(String[] args) {
// Create a collection
List v = new Vector();
//Vector v = new Vector();
// The default volume 10
v.add(1);
v.add(2);
v.add(3);
v.add(4);
v.add(5);
v.add(6);
v.add(7);
v.add(8);
v.add(9);
v.add(10);
// Expand when it's full ( After the expansion is 20)
v.add(11);
Iterator it = v.iterator();
while (it.hasNext()){
Object object = it.next();
System.out.print(object + " ");
}// Output results ;1 2 3 4 5 6 7 8 9 10 11
/*
How to make a thread unsafe ArrayList Set to thread safe ?
Use the collection utility class :java.util.Collections;
java.util.Collection It's a collection interface
java.util.Collections It's a collection tool class
*/
List mylist = new ArrayList();// Non thread safe
// Become thread safe
Collections.synchronizedList(mylist);
//myList Collections are thread safe
mylist.add("111");
mylist.add("222");
mylist.add("333");
}
}
Generic
The grammatical mechanism of generics , Only works during the compilation phase of the program , Just for the compiler .( Runtime generics are useless )
The advantages of using generics :
- The element types stored in the collection are unified
- The element type taken from the collection is the type specified by the generic , There's no need for a lot of downward transformation
shortcoming
The disadvantages of generics : Leads to a lack of diversity in the elements stored in the collection !
Be careful : In most businesses , The element types of sets are still uniform .
package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest01 {
public static void main(String[] args) {
// Don't use generic mechanisms , Analysis of the shortcomings of the program
List myList = new ArrayList();
// Prepare for
Cat c = new Cat();
Bird b = new Bird();
// Add objects to the collection
myList.add(c);
myList.add(b);
// Ergodic set , Take out Cat Let her catch mice , Take out Bird Let her fly !
Iterator it = myList.iterator();
while (it.hasNext()){
Object obj = it.next();
// Forced transformation
if (obj instanceof Animal){
Animal a = (Animal)obj;
a.move();
}
if(obj instanceof Cat){
Cat c1 = (Cat)obj;
c1.catMouse();
}
if(obj instanceof Bird){
Bird b1 = (Bird)obj;
b1.fly();
}
}
// Output results :
// Animals are moving !
// The cat is catching mice !
// Animals are moving !
// The birds are flying !
}
}
class Animal{
// Method of parent class
public void move(){
System.out.println(" Animals are moving !");
}
}
class Cat extends Animal{
// Unique method
public void catMouse(){
System.out.println(" The cat is catching mice !");
}
}
class Bird extends Animal{
// Unique method
public void fly(){
System.out.println(" The birds are flying !");
}
}
package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest02 {
public static void main(String[] args) {
// Use generics List<Animal2> after , Express List Only storage is allowed in the collection Animal Data of type
// Specifies the data type of data stored in the collection with a generic type
List<Animal2> myList2 = new ArrayList<Animal2>();
// Appoint list Collection can only store Animal
//myList2.add("abc"); Report errors
Cat2 c2 = new Cat2();
Bird2 b2 = new Bird2();
myList2.add(c2);
myList2.add(b2);
// Acquisition iterator
// This represents iterator iteration Animal type
Iterator<Animal2> it2 = myList2.iterator();
while (it2.hasNext()){
// After using generics , The data type returned by each iteration is Animal type
Animal2 a2 = it2.next();
// If used directly Animal type , There is no need to cast , Call directly
//a2.move();
if(a2 instanceof Cat2){
Cat2 x = (Cat2)a2;
x.catMouse();
}
if (a2 instanceof Bird2){
Bird2 y = (Bird2)a2;
y.fly();
}
}
// Output results :
// The cat is catching mice !
// The birds are flying !
}
}
class Animal2{
// Method of parent class
public void move(){
System.out.println(" Animals are moving !");
}
}
class Cat2 extends Animal2{
// Unique method
public void catMouse(){
System.out.println(" The cat is catching mice !");
}
}
class Bird2 extends Animal2{
// Unique method
public void fly(){
System.out.println(" The birds are flying !");
}
}
Automatic type inference
JDK8 And then introduced : Automatic type inference mechanism ( Also known as the diamond expression )
package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GenericTest03 {
public static void main(String[] args) {
//ArrayList< The type here automatically infers , Premise is JDK8 After that >
// Automatic type inference
//List<Animal2> myList3 = new ArrayList<Animal2>();
List<Animal2> myList3 = new ArrayList<>();
myList3.add(new Animal2());
myList3.add(new Cat2());
myList3.add(new Bird2());
// Traverse
Iterator<Animal2> it3 = myList3.iterator();
while (it3.hasNext()){
Animal2 aa = it3.next();
aa.move();
}
List<String> stringList = new ArrayList<>();
// Type mismatch
//stringList.add(new Cat2());
//stringList.add(123);
stringList.add("http://www.163.com");
stringList.add("http://www.baidu.com");
stringList.add("http://www.bjpownode.com");
Iterator<String> its = stringList.iterator();
while (its.hasNext()){
String s = its.next();
String newString = s.substring(7);
System.out.println(newString);
}
/**
* Running results :
* Animals are moving !
* Animals are moving !
* Animals are moving !
* www.163.com
* www.baidu.com
* www.bjpownode.com
*/
}
}
Custom generics
When you customize generics ,<>( Angle brackets ) In is an identifier , Write casually
java The source code often appears in
1.E yes Element Word initials
2.T yes Type Word initials
package se3.collection;
public class GenericTest04< The identifier can be written casually > {
public void doSome( The identifier can be written casually o){
System.out.println(o);
}
public static void main(String[] args) {
GenericTest04<String> gt = new GenericTest04<>();
//gt.doSome(100); Report errors : Type mismatch
gt.doSome("qwq");// Output qwq
//==========================================
GenericTest04<Integer> gt2 = new GenericTest04<>();
//gt2.doSome(" APO "); Report errors : Type mismatch
gt2.doSome(100);// Output 100
MyIterator<String> mi = new MyIterator<>();
String s1 = mi.get();
//Animal aaa2 = mi2.get(); Report errors
MyIterator<Animal> mi2 = new MyIterator<>();
Animal aaa = mi2.get();
//String s2 = mi2.get(); Report errors
// Without generics, it's just Object type
GenericTest04 gt3 = new GenericTest04();
gt3.doSome(new Object());
gt3.doSome(200);
gt3.doSome(" APO ");
}
}
class MyIterator<T>{
public T get(){
return null;
}
}
Use together foreach
package se3.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ForEachTest01 {
public static void main(String[] args) {
// establish List aggregate
List<String> stringList = new ArrayList<>();
// Additive elements
stringList.add("hello");
stringList.add(" APO ");
stringList.add("123");
// Traverse , Using the iterator approach
Iterator<String> it = stringList.iterator();
while (it.hasNext()){
String s = it.next();
System.out.print(s + " ");
}
System.out.println();
// Using subscripts ( Only for sets with subscripts )
for (int i = 0; i < stringList.size(); i++) {
System.out.print(stringList.get(i) + " ");
}
System.out.println();
// Use foreach
for (String s : stringList) {// Because generics use Sting type , So it is String s
System.out.print(s + " ");
}
System.out.println();
List<Integer> list = new ArrayList<>();
list.add(100);
list.add(200);
list.add(300);
for (Integer i : list){//i Represents the elements in the set
System.out.print(i + " ");
}
/**
* Output results :
* hello APO 123
* hello APO 123
* hello APO 123
* 100 200 300
*/
}
}