Comparación del marco de recopilación avanzado intermedio de Java

Escribir al frente

Hola a todos, hoy estoy aquí para actualizar nuevamente el producto seco, y no se ha actualizado en dos días. En los últimos días, recopilé y clasifiqué el contenido de conocimiento de la cuenta oficial para actualizarlo a continuación, para asegurarme de que cada actualización beneficiará a todos los lectores.

En los últimos días, también he hecho todo lo posible para prepararme para los proyectos corporativos recientes organizados en el grupo para asegurar que cada socio pequeño que participó en el primer lote realmente pueda mejorar sus habilidades y ganar experiencia en proyectos reales. Así que la cuenta oficial se retrasó dos días. Supongo que si no actualizas los productos secos hoy, los amigos tendrán que comprobarlo, ¡jaja!

El contenido traído a organizar hoy es "Comparación entre marcos de colección de Java". También es la pregunta favorita del entrevistador en la entrevista El contenido de hoy se espera que cada pequeño socio lo domine, y lo más importante.

Comparación del marco de recopilación avanzado intermedio de Java

La relación entre el marco de la colección JAVA

1. ArrayList 与 HashSet

1.1 ¿Existe una orden

① ArrayList: en orden

② HashSet: Sin orden

Código:


 1ArrayList<Integer> numberList =new ArrayList<Integer>();
 2//List中的数据按照插入顺序存放
 3System.out.println("----------List----------");
 4System.out.println("向 List 中插入 9 5 1");
 5numberList.add(9);
 6numberList.add(5);
 7numberList.add(1);
 8System.out.println("List 按照顺序存放数据:");
 9System.out.println(numberList);
10System.out.println("----------Set----------");
11HashSet<Integer> numberSet =new HashSet<Integer>();
12System.out.println("向Set 中插入9 5 1");
13//Set中的数据不是按照插入顺序存放
14numberSet.add(9);
15numberSet.add(5);
16numberSet.add(1);
17System.out.println("Set 不是按照顺序存放数据:");
18System.out.println(numberSet);

1.2 ¿Puede repetirse

① Los datos de la Lista se pueden repetir

② Los datos del conjunto no se pueden repetir

Los criterios para el juicio repetido son:

① Primero mira si el código hash es el mismo

② Si el código hash es diferente, se considera un dato diferente

③ Si el código hash es el mismo, entonces compare iguales, si iguales son iguales, son los mismos datos, de lo contrario son datos diferentes

Código:


 1ArrayList<Integer> numberList = newArrayList<Integer>();
 2//List中的数据可以重复
 3System.out.println("----------List----------");
 4System.out.println("向List 中插入 9 9");
 5numberList.add(9);
 6numberList.add(9);
 7System.out.println("List 中出现两个9:");
 8System.out.println(numberList);
 9System.out.println("----------Set----------");
10HashSet<Integer> numberSet =newHashSet<Integer>();
11System.out.println("向Set 中插入9 9");
12// Set中的数据不能重复
13numberSet.add(9);
14numberSet.add(9);
15System.out.println("Set 中只会保留一个 9:");
16System.out.println(numberSet);
  1. ArrayList 与 LinkedList

2.1 La diferencia entre ArrayList y LinkedList

① La inserción y eliminación de datos de ArrayList es lenta.

② Insertar LinkedList, eliminar datos rápidamente

③ ArrayList es una estructura secuencial, por lo que el posicionamiento es muy rápido. Al igual que la ubicación de un cine, una vez que tenga una entrada para el cine, puede encontrar la ubicación. LinkedList es una estructura de lista enlazada, como una cadena de cuentas en su mano. Para encontrar las cuentas 99, debe contarlas una por una, por lo que el posicionamiento es lento.

2.2 Insertar datos

Código:


 1public static void main(String[] args) {
 2      List<Integer> l;
 3      l = new ArrayList<>();
 4      insertFirst(l, "ArrayList");
 5      l = new LinkedList<>();
 6      insertFirst(l, "LinkedList");
 7}
 8private static void insertFirst(List<Integer> l, String type) {
 9      int total = 1000 * 100;
10      final int number = 5;
11      //获取当前系统时间
12      long start = System.currentTimeMillis();
13      for (int i = 0; i < total; i++) {
14      l.add(0, number);
15}
16      long end = System.currentTimeMillis();
17      System.out.printf("在%s 最前面插入%d条数据,总共耗时 %d 毫秒 %n", type, total, end - start);
18}

2.3 Datos de posicionamiento

Código:


 1public static void main(String[] args) {
 2     List<Integer> l;
 3     l = new ArrayList<>();
 4     modify(l, "ArrayList");
 5     l = new LinkedList<>();
 6     modify(l, "LinkedList");
 7}
 8private static void modify(List<Integer> l, String type) {
 9    int total = 100 * 1000;
10    int index = total/2;
11    final int number = 5;
12    //初始化
13    for (int i = 0; i < total; i++) {
14       l.add(number);
15    }
16    long start = System.currentTimeMillis();
17    for (int i = 0; i < total; i++) {
18      int n = l.get(index);
19      n++;
20      l.set(index, n);
21    }
22    long end = System.currentTimeMillis();
23    System.out.printf("%s总长度是%d,定位到第%d个数据,取出来,加1,再放回去%n 重复%d遍,总共耗时 %d 毫秒 %n", type,total, index,total, end - start);
24    System.out.println();
25}
  1. HashMap 与 HashTable

3.1 La diferencia entre HashMap y Hashtable

Punto común: HashMap y Hashtable implementan la interfaz Map, ambos son pares clave-valor para guardar datos

diferencia:

Diferencia 1:

① HashMap puede almacenar nulo

② Hashtable no puede almacenar nulo

Diferencia 2:

① HashMap no es una clase segura para subprocesos

② Hashtable es una clase segura para subprocesos

Código:


1//HashMap和Hashtable都实现了Map接口,都是键值对保存数据的方式
2HashMap<String,String> hashMap = newHashMap<String,String>();
3//HashMap可以用null作key,作value
4hashMap.put(null, "123");
5hashMap.put("123", null);
6Hashtable<String,String> hashtable = newHashtable<String,String>();
7//Hashtable不能用null作key,不能用null作value
8hashtable.put(null, "123");
9hashtable.put("123", null);
  1. conjunto

4.1 tipos de conjuntos

① HashSet: desordenado

② LinkedHashSet: Según el orden de inserción

③ TreeSet: ordenar de pequeño a grande

Código:


 1HashSet<Integer> numberSet1 =newHashSet<Integer>();
 2//HashSet中的数据不是按照插入顺序存放
 3numberSet1.add(88);
 4numberSet1.add(8);
 5numberSet1.add(888);
 6System.out.println(numberSet1);
 7LinkedHashSet<Integer> numberSet2 =newLinkedHashSet<Integer>();
 8//LinkedHashSet中的数据是按照插入顺序存放
 9numberSet2.add(88);
10numberSet2.add(8);
11numberSet2.add(888);
12System.out.println(numberSet2);
13TreeSet<Integer> numberSet3 =newTreeSet<Integer>();
14//TreeSet 中的数据是进行了排序的
15numberSet3.add(88);
16numberSet3.add(8);
17numberSet3.add(888);
18System.out.println(numberSet3);

Supongo que te gusta

Origin blog.51cto.com/15064450/2602794
Recomendado
Clasificación