Inizializzazione di un elenco in Java

Inizializzazione di un elenco in Java

IL Java.util.List è un'interfaccia figlia di Collezione . È una raccolta ordinata di oggetti in cui è possibile archiviare valori duplicati. Poiché List preserva l'ordine di inserimento, consente l'accesso posizionale e l'inserimento di elementi. L'interfaccia dell'elenco è implementata da Lista di array , Lista collegata , Vettore E Pila classi.

listinterfacejava

List è un'interfaccia e le istanze di List possono essere create nei seguenti modi:

 List a = new ArrayList(); List b = new LinkedList(); List c = new Vector(); List d = new Stack(); 

Di seguito sono riportati i seguenti modi per inizializzare un elenco:

  1. Utilizzando il metodo List.add()

    Poiché list è un'interfaccia, non è possibile istanziarla direttamente. Tuttavia, è possibile creare oggetti di quelle classi che hanno implementato questa interfaccia e istanziarli.

    Poche classi che hanno implementato l'interfaccia List lo sono Stack, ArrayList, LinkedList, Vettore eccetera.

    Sintassi:

     List list=new ArrayList(); List llist=new LinkedList(); List stack=new Stack(); 

    Esempi:




    import> java.util.*;> import> java.util.function.Supplier;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // For ArrayList> > List list => new> ArrayList();> > list.add(> 1> );> > list.add(> 3> );> > System.out.println(> 'ArrayList : '> + list.toString());> > > // For LinkedList> > List llist => new> LinkedList();> > llist.add(> 2> );> > llist.add(> 4> );> > System.out.println(> 'LinkedList : '> + llist.toString());> > > // For Stack> > List stack => new> Stack();> > stack.add(> 3> );> > stack.add(> 1> );> > System.out.println(> 'Stack : '> + stack.toString());> > }> }>

    Produzione:

     ArrayList : [1, 3] LinkedList : [2, 4] Stack : [3, 1] 

    Inizializzazione della doppia parentesi graffa può essere utilizzato anche per eseguire il lavoro di cui sopra.

    Sintassi:

     List list=new ArrayList(){{ add(1); add(2); add(3); }}; 

    Esempi:




    import> java.util.*;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // For ArrayList> > List list => new> ArrayList() {{> > add(> 1> );> > add(> 3> );> > } };> > System.out.println(> 'ArrayList : '> + list.toString());> > > // For LinkedList> > List llist => new> LinkedList() {{> > add(> 2> );> > add(> 4> );> > } };> > System.out.println(> 'LinkedList : '> + llist.toString());> > > // For Stack> > List stack => new> Stack() {{> > add(> 3> );> > add(> 1> );> > } };> > System.out.println(> 'Stack : '> + stack.toString());> > }> }>

    Produzione:

     ArrayList : [1, 3] LinkedList : [2, 4] Stack : [3, 1] 
  2. Utilizzando Arrays.asList()

    • Creazione di un elenco immutabile

      Array.asList() crea un elenco immutabile da un array. Quindi può essere utilizzato per creare un'istanza di un elenco con un array.

      Sintassi:

      List list=Arrays.asList(1, 2, 3); 

      Esempi:




      import> java.util.Arrays;> import> java.util.List;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Instantiating List using Arrays.asList()> > List list = Arrays.asList(> 1> ,> 2> ,> 3> );> > > // Print the list> > System.out.println(> 'List : '> + list.toString());> > }> }>

      Produzione:

       List : [1, 2, 3] 
    • Creazione di un elenco mutabile

      Sintassi:

      List list=new ArrayList(Arrays.asList(1, 2, 3)); 

      Esempi:




      import> java.util.ArrayList;> import> java.util.Arrays;> import> java.util.List;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Creating a mutable list using Arrays.asList()> > List list => new> ArrayList(> > Arrays.asList(> 1> ,> 2> ,> 3> ));> > > // Print the list> > System.out.println(> 'List : '> + list.toString());> > > list.add(> 5> );> > > // Print the list> > System.out.println(> 'Modified list : '> + list.toString());> > }> }>

      Produzione:

       List : [1, 2, 3] Modified list : [1, 2, 3, 5] 
  3. Utilizzo dei metodi della classe Collections

    Esistono vari metodi nella classe Collections che possono essere utilizzati per creare un'istanza di un elenco. Sono:

    1. Utilizzando Collections.addAll()

      Collezioni la classe ha un metodo statico Aggiungi tutto() che può essere utilizzato per inizializzare un elenco. Collezioni.addAll() accettare un numero qualsiasi di elementi dopo che è stato specificato con la Collection in cui gli elementi devono essere inseriti.

      Sintassi:

      List list = Collections.EMPTY_LIST; Collections.addAll(list = new ArrayList(), 1, 2, 3, 4); 

      Esempi:




      import> java.util.*;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Create an empty list> > List list => new> ArrayList();> > > // Instantiating list using Collections.addAll()> > Collections.addAll(list,> 1> ,> 2> ,> 3> ,> 4> );> > > // Print the list> > System.out.println(> 'List : '> + list.toString());> > }> }>

      Produzione:

       List : [1, 2, 3, 4] 
    2. Utilizzo di Collections.unmodifyingList()

      Collections.unmodifyingList() restituisce una lista che non può essere modificata, ovvero non può né aggiungere né eliminare un elemento. Qualsiasi tentativo di modificare l'elenco genererà un UnsupportedOperationExample.

      Sintassi:

      List list = Collections .unmodifiableList(Arrays.asList(1, 2, 3)); 

      Esempio 1:




      import> java.util.*;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Creating the list> > List list = Collections.unmodifiableList(> > Arrays.asList(> 1> ,> 2> ,> 3> ));> > > // Print the list> > System.out.println(> 'List : '> + list.toString());> > }> }>

      Produzione:

       List : [1, 2, 3] 

      Esempio 2:




      import> java.util.*;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > try> {> > // Creating the list> > List list = Collections.unmodifiableList(> > Arrays.asList(> 1> ,> 2> ,> 3> ));> > > // Print the list> > System.out.println(> 'List : '> + list.toString());> > > // Trying to modify the list> > System.out.println(> 'Trying to modify the list'> );> > list.set(> 0> , list.get(> 0> ));> > }> > > catch> (Exception e) {> > System.out.println(> 'Exception : '> + e);> > }> > }> }>

      Produzione:

       List : [1, 2, 3] Trying to modify the list Exception : java.lang.UnsupportedOperationException 
    3. Utilizzando Collections.singletonList()

      Collezioni.singletonList() restituisce una lista immutabile composta da un solo elemento.

      Sintassi:

      List list = Collections.singletonList(2); 

      Esempio 1:




      import> java.util.*;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Creating the list> > List list = Collections.singletonList(> 2> );> > > // Print the list> > System.out.println(> 'List : '> + list.toString());> > }> }>

      Produzione:

       List : [2] 
  4. Utilizzo di Java 8Stream

    Con l'introduzione dello Stream e della programmazione funzionale in Java 8, ora è possibile costruire qualsiasi flusso di oggetti e quindi raccoglierli come un elenco.

    Sintassi:

     1. List list = Stream.of(1, 2, 3) .collect(Collectors.toList()); 2. List list = Stream.of(1, 2, 3) .collect(Collectors.toCollection(ArrayList::new)); 3. List list = Stream.of(1, 2, 3, 4) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); 

    Esempi:




    import> java.util.*;> import> java.util.stream.Collectors;> import> java.util.stream.Stream;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Creating a List using Syntax 1> > List list1 = Stream.of(> 1> ,> 2> ,> 3> )> > .collect(Collectors.toList());> > > // Printing the list> > System.out.println(> 'List using Syntax 1: '> > + list1.toString());> > > // Creating a List using Syntax 2> > List list2 = Stream> > .of(> 3> ,> 2> ,> 1> )> > .collect(> > Collectors> > .toCollection(ArrayList::> new> ));> > > // Printing the list> > System.out.println(> 'List using Syntax 2: '> > + list2.toString());> > > // Creating a List using Syntax 3> > List list3 = Stream> > .of(> 1> ,> 2> ,> 3> ,> 4> )> > .collect(> > Collectors> > .collectingAndThen(> > Collectors.toList(),> > Collections::unmodifiableList));> > > // Printing the list> > System.out.println(> 'List using Syntax 3: '> > + list3.toString());> > }> }>

    Produzione:

     List using Syntax 1: [1, 2, 3] List using Syntax 2: [3, 2, 1] List using Syntax 3: [1, 2, 3, 4] 
  5. Utilizzo di Java 9 List.of()

    Java 9 ha introdotto il metodo List.of() che accetta un numero qualsiasi di argomenti e ne costruisce un elenco compatto e immodificabile.

    Sintassi:

    List unmodifiableList = List.of(1, 2, 3); 

    Esempi:




    import> java.util.List;> > public> class> GFG {> > public> static> void> main(String args[])> > {> > > // Creating a list using List.of()> > List unmodifiableList = List.of(> 1> ,> 2> ,> 3> );> > > // Printing the List> > System.out.println(> 'List : '> > + unmodifiableList.toString());> > }> }>

    PRODUZIONE:

     [1, 2, 3]