logo

Come creare un elenco generico in Java?

Java è un potente linguaggio di programmazione che può essere utilizzato per creare una vasta gamma di app desktop, online e mobili. L'interfaccia List è una delle strutture dati principali di Java. Un elenco è un gruppo di elementi disposti in un determinato ordine e può includere duplicati. Vedremo come creare un elenco generico in Java in questo tutorial.

Cos'è un elenco generico in Java?

Una lista generica in Java è un raggruppamento di elementi di un tipo particolare. ArrayList, LinkedList e Vector sono solo alcune delle classi che implementano l'interfaccia generale List, specificata nel pacchetto java.util. Gli sviluppatori possono creare una raccolta di componenti di qualsiasi tipo e trarre vantaggio dall'indipendenza dai tipi in fase di compilazione utilizzando un elenco generico.

Creazione di un elenco generico in Java

Per creare un elenco generico in Java, dobbiamo seguire questi passaggi:

Passo 1: Importa i pacchetti richiesti

In Java, dobbiamo importare il pacchetto java.util per utilizzare l'interfaccia List.

Passo 2: Dichiarare la lista

La Lista deve poi essere dichiarata utilizzando la sintassi generale. Tra parentesi angolari (>), descriviamo il tipo di elementi che vogliamo memorizzare nella Lista.

mylive cricket

Per creare un elenco di numeri, ad esempio, potremmo dichiararlo come segue:

 List integerList = new ArrayList(); 

Questo dichiara un elenco denominato integerList che può memorizzare elementi di tipo Integer. Abbiamo utilizzato la classe ArrayList per implementare l'interfaccia List.

Passaggio 3: Aggiungi elementi alla lista

Dopo aver dichiarato la Lista, possiamo aggiungervi elementi utilizzando il metodo add().

Ad esempio, per aggiungere un numero intero a integerList, utilizzeremo il seguente codice:

 integerList.add(10); 

Aggiunge il valore intero 10 alla fine della Lista.

Passaggio 4: Accedere agli elementi della Lista

Possiamo accedere agli elementi della Lista utilizzando il metodo get().

Ad esempio, per ottenere il primo elemento di integerList, utilizzeremmo il seguente codice:

decodifica js base64
 int firstElement = integerList.get(0); 

Questo recupera il primo elemento della Lista e lo memorizza nella variabile firstElement.

Passaggio 5: Scorri l'elenco

Possiamo scorrere gli elementi della Lista usando un ciclo for.

Ad esempio, per stampare tutti gli elementi di integerList, utilizzeremmo il seguente codice:

 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();>

In questo esempio, l'utente immette 3 come numero di stringhe da aggiungere all'elenco. All'utente viene quindi richiesto dal programma di inserire ciascuna stringa individualmente. Il programma stampa ogni stringa nell'elenco sulla console quando tutte le stringhe sono state aggiunte all'elenco.

Vantaggi dell'utilizzo di elenchi generici

L'utilizzo di elenchi generici in Java presenta diversi vantaggi:

Tipo di sicurezza: Specificando la tipologia di elementi che la Lista può contenere; possiamo evitare errori di runtime causati dall'aggiunta di elementi del tipo sbagliato.

Riutilizzabilità: Gli elenchi generici possono essere utilizzati con qualsiasi tipo di elemento, rendendoli una struttura dati flessibile e riutilizzabile.

Prestazione: Molte implementazioni di List, come ArrayList, offrono tempi di accesso e modifica rapidi.

Familiarità: Gli elenchi sono una struttura dati comunemente utilizzata in informatica, il che li rende una scelta familiare e intuitiva per molti sviluppatori.