logo

Com crear una llista genèrica a Java?

Java és un llenguatge de programació potent que es pot utilitzar per crear una gran varietat d'aplicacions d'escriptori, en línia i mòbils. La interfície de llista és una de les estructures de dades bàsiques de Java. Una llista és un grup d'elements que s'organitzen en un ordre determinat i poden incloure duplicats. Veurem com crear una llista genèrica en Java en aquest tutorial.

Què és una llista genèrica a Java?

Una llista genèrica en Java és una agrupació d'elements d'un tipus particular. ArrayList, LinkedList i Vector són només algunes de les classes que implementen la interfície general List, que s'especifica al paquet java.util. Els desenvolupadors poden crear una col·lecció de components de qualsevol tipus i beneficiar-se de la seguretat de tipus en temps de compilació mitjançant una llista genèrica.

Creació d'una llista genèrica en Java

Per crear una llista genèrica a Java, hem de seguir aquests passos:

Pas 1: Importa els paquets necessaris

A Java, hem d'importar el paquet java.util per utilitzar la interfície List.

Pas 2: Declarar la llista

Aleshores, la llista s'ha de declarar utilitzant la sintaxi general. Dins dels claudàtors angulars (>), descrivim el tipus d'elements que volem emmagatzemar a la llista.

Per crear una llista de números, per exemple, podríem declarar-la de la següent manera:

 List integerList = new ArrayList(); 

Això declara una llista anomenada integerList que pot emmagatzemar elements del tipus Integer. Hem utilitzat la classe ArrayList per implementar la interfície List.

Pas 3: Afegeix elements a la llista

Després de declarar la llista, podem afegir-hi elements mitjançant el mètode add().

Per exemple, per afegir un nombre enter a la llista integerList, utilitzaríem el codi següent:

 integerList.add(10); 

Afegeix el valor enter 10 al final de la llista.

bloquejar anuncis de youtube Android

Pas 4: Accés als elements de la Llista

Podem accedir als elements de la llista mitjançant el mètode get().

Per exemple, per obtenir el primer element de la integerList, utilitzaríem el codi següent:

 int firstElement = integerList.get(0); 

Això recupera el primer element de la llista i l'emmagatzema a la variable firstElement.

Pas 5: Recorre la llista

Podem iterar sobre els elements de la llista utilitzant un bucle for.

Per exemple, per imprimir tots els elements de la integerList, utilitzaríem el codi següent:

 for (int i = 0; i <integerlist.size(); i++) { system.out.println(integerlist.get(i)); } < pre> <p>It iteratively prints each element of the List to the console.</p> <p>Any Java developer must possess the fundamental ability to create a generic List in Java. You can create a List of any type and carry out activities like adding and accessing entries as well as iterating over the List by following the instructions provided in this article. Generic Lists offer type safety and enable more robust and maintainable programming.</p> <p>TheJava programme builds a generic List of strings, elements are added to it, and the result is printed to the console. The user is prompted to enter each string when the programme asks for their input on how many strings to add to the list.</p> <p> <strong>GenericListExample.java</strong> </p> <pre> import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class GenericListExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(&apos;How many strings do you want to add to the list? &apos;); int numStrings = scanner.nextInt(); List stringList = new ArrayList(); for (int i = 0; i <numstrings; i++) { system.out.print('enter string ' + (i+1) ': '); inputstring="scanner.next();" stringlist.add(inputstring); } system.out.println('the strings in the list are:'); for (string str : stringlist) system.out.println(str); < pre> <p> <strong>Output:</strong> </p> <pre> How many strings do you want to add to the list? 3 Enter string 1: apple Enter string 2: banana Enter string 3: orange The strings in the list are: apple banana orange </pre> <p>In this example, the user inputs 3 as the number of strings to add to the list. The user is then prompted by the programme to enter each string individually. The programme prints each string in the list to the console when all strings have been added to the list.</p> <h2>Advantages of Using Generic Lists</h2> <p>Using generic Lists in Java has several advantages:</p> <p> <strong>Type safety:</strong> By specifying the type of elements that the List can contain; we can avoid runtime errors caused by adding elements of the wrong type.</p> <p> <strong>Reusability:</strong> Generic Lists can be used with any type of element, making them a flexible and reusable data structure.</p> <p> <strong>Performance:</strong> Many List implementations, such as ArrayList, offer fast access and modification times.</p> <p> <strong>Familiarity:</strong> Lists are a commonly used data structure in computer science, making them a familiar and intuitive choice for many developers.</p> <hr></numstrings;></pre></integerlist.size();>

En aquest exemple, l'usuari introdueix 3 com a nombre de cadenes per afegir a la llista. Aleshores, el programa demana a l'usuari que introdueixi cada cadena individualment. El programa imprimeix cada cadena de la llista a la consola quan totes les cadenes s'han afegit a la llista.

Avantatges d'utilitzar llistes genèriques

L'ús de llistes genèriques a Java té diversos avantatges:

Tipus de seguretat: En especificar el tipus d'elements que pot contenir la Llista; podem evitar errors d'execució causats afegint elements del tipus incorrecte.

Reutilitzabilitat: Les llistes genèriques es poden utilitzar amb qualsevol tipus d'element, fent-les una estructura de dades flexible i reutilitzable.

Rendiment: Moltes implementacions de llista, com ara ArrayList, ofereixen temps d'accés i modificació ràpids.

Coneixement: Les llistes són una estructura de dades d'ús habitual en informàtica, cosa que les converteix en una opció familiar i intuïtiva per a molts desenvolupadors.