Jak zrobić nową listę w Javie

Tworzymy Set jako:

Set myset = new HashSet()

Jak stworzyć List w Javie?

Author: Oleksandr Pyrohov, 2009-05-13

24 answers

List myList = new ArrayList();

Lub z generics ( Java 7 lub później)

List<MyType> myList = new ArrayList<>();

Lub z generics (stare wersje Javy)

List<MyType> myList = new ArrayList<MyType>();
 1032
Author: Dan Vinton,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-14 14:28:21

Dodatkowo, jeśli chcesz utworzyć listę, która zawiera rzeczy (choć będzie miała stały rozmiar):

List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
 498
Author: Aaron Maenpaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-13 23:45:43

Podsumuję i coś dodam:

JDK

1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")

Guajawa

1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});

Lista Niezmienna

1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder()                                      // Guava
            .add("A")
            .add("B").build();
3. ImmutableList.of("A", "B");                                  // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C"));     // Guava

Empty immutable List

1. Collections.emptyList();
2. Collections.EMPTY_LIST;

Lista znaków

1. Lists.charactersOf("String")                                 // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String"))  // Guava

Lista liczb całkowitych

Ints.asList(1,2,3);                                             // Guava
 188
Author: Sergii Shevchyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-13 12:40:56

W Javie 8

Aby utworzyć niepustą Listę o stałym rozmiarze (operacje takie jak Dodaj, usuń, itp., nie są obsługiwane):

List<Integer> list = Arrays.asList(1, 2); // but, list.set(...) is supported

Aby utworzyć niepustą zmienną listę:

List<Integer> list = new ArrayList<>(Arrays.asList(3, 4));

W Javie 9

Używanie nowego List.of(...) statyczne metody fabryczne:

List<Integer> immutableList = List.of(1, 2);

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

W Javie 10

Użycie typ zmiennej lokalnej wnioskowanie :

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

I stosuj najlepsze praktyki...

Nie używaj typów raw

Od Java 5, generyki były częścią języka - powinieneś ich używać:

List<String> list = new ArrayList<>(); // Good, List of String

List list = new ArrayList(); // Bad, don't do that!

Program do interfejsów

Na przykład, program do interfejsu List:

List<Double> list = new ArrayList<>();

Zamiast:

ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!
 70
Author: Oleksandr Pyrohov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-20 13:11:45

Najpierw przeczytaj to , następnie przeczytaj to i to. 9 razy na 10 użyjesz jednej z tych dwóch implementacji.

W rzeczywistości, wystarczy przeczytać Przewodnik Sun do zbioru Framework .

 31
Author: Adam Jaskiewicz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-13 15:28:50
//simple example creating a list form a string array

String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};

List mylist = Arrays.asList(myStrings );

//getting an iterator object to browse list items

Iterator itr= mylist.iterator();

System.out.println("Displaying List Elements,");

while(itr.hasNext())

  System.out.println(itr.next());
 21
Author: Blerta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-13 16:07:32

Od Javy 7 masz wnioskowanie typu do tworzenia instancji generycznych , więc nie ma potrzeby powielania parametrów generycznych po prawej stronie przypisania:

List<String> list = new ArrayList<>();

Listę o stałym rozmiarze można zdefiniować jako:

List<String> list = Arrays.asList("foo", "bar");

Dla list niezmiennych możesz użyć biblioteki Guava :

List<String> list = ImmutableList.of("foo", "bar");
 21
Author: Vitalii Fedorenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-28 12:15:59

List jest tylko interfejsem tak jak Set .

Podobnie jak HashSet jest implementacją zestawu, który ma pewne właściwości w odniesieniu do wydajności dodawania / wyszukiwania / usuwania, ArrayList jest gołą implementacją listy.

Jeśli przyjrzysz się dokumentacji dla odpowiednich interfejsów, znajdziesz "wszystkie znane klasy implementujące" i możesz zdecydować, która z nich jest bardziej odpowiednia dla Twoich potrzeb.

Są szanse, że to ArrayList .

 20
Author: Sorin Mocanu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-13 15:55:26

List jest interfejsem podobnym do Set i ma ArrayList i LinkedList jako implementacje ogólnego przeznaczenia.

Możemy utworzyć listę jako:

 List<String> arrayList = new ArrayList<>();
 List<String> linkedList = new LinkedList<>(); 

Możemy również utworzyć listę o stałym rozmiarze jako:

List<String> list = Arrays.asList("A", "B", "C");

Prawie zawsze używalibyśmy ArrayList W przeciwieństwie do LinkedList implementacji:

  1. LinkedList zużywa dużo miejsca na obiekty i działa źle, gdy mamy dużo elementów.
  2. każda operacja indeksowana w LinkedList wymaga czasu O (n) w porównaniu do O(1) w ArrayList.
  3. Aby uzyskać więcej informacji, sprawdź ten link .

Lista utworzona przez Arrays.asList powyżej nie może być modyfikowana strukturalnie, ale jej elementy nadal mogą być modyfikowane.

Java 8

Zgodnie z doc , metoda Collections.unmodifiableList zwraca niezmodyfikowany widok podanej listy. Możemy to uzyskać jak:

Collections.unmodifiableList(Arrays.asList("A", "B", "C"));

Java 9

W przypadku, gdy używamy Java 9 wtedy:

List<String> list = List.of("A", "B");

Java 10

W przypadku, gdy jesteśmy na Java 10 następnie metoda Collectors.unmodifiableList zwróci instancję prawdziwie niezmodyfikowanej listy wprowadzonej w Javie 9. Sprawdź tę odpowiedź aby uzyskać więcej informacji na temat różnicy w Collections.unmodifiableList vs Collectors.unmodifiableList W } Java 10 .

 18
Author: akhil_mittal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-03 05:37:59

Czasami-ale tylko bardzo rzadko - zamiast nowej ArrayList możesz chcieć nowej Listy LinkedList. Zacznij od ArrayList i jeśli masz problemy z wydajnością i dowody, że lista jest problemem , a wiele dodawania i usuwania do tej listy - to - nie wcześniej-przełącz się na LinkedList i zobacz, czy coś się poprawi. Ale przede wszystkim trzymaj się ArrayList i wszystko będzie dobrze.

 9
Author: Carl Manaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-13 15:29:00
List list = new ArrayList();

Lub z generykami

List<String> list = new ArrayList<String>();

Można oczywiście zamienić string na dowolny typ zmiennej, np. Integer.

 9
Author: Paulo Guedes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-03 05:46:12

Jeden przykład:

List somelist = new ArrayList();

Możesz spojrzeć na javadoc dla listy i znaleźć wszystkie znane klasy implementujące interfejsu List, które są zawarte w java api.

 7
Author: Alex B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-13 15:14:53

Używając Google Collections , możesz użyć następujących metod w Lists class

import com.google.common.collect.Lists;

// ...

List<String> strings = Lists.newArrayList();

List<Integer> integers = Lists.newLinkedList();

Istnieją przeciążenia dla inicjalizacji varargs i inicjalizacji z Iterable<T>.

Zaletą tych metod jest to, że nie musisz jawnie określać parametru generycznego, tak jak w przypadku konstruktora - kompilator wywnioskuje go z typu zmiennej.

 7
Author: Ben Lings,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-04 11:55:27

Jako opcja możesz użyć inicjalizacji podwójnego nawiasu:

List<String> list = new ArrayList<String>(){
  {
   add("a");
   add("b");
  }
};
 7
Author: angry_gopher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-11 11:17:00
List<Object> nameOfList = new ArrayList<Object>();

Musisz zaimportować List i ArrayList.

 6
Author: jp093121,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-12 23:26:40

Więcej opcji, aby zrobić to samo z Java 8, nie lepiej, nie gorzej, po prostu inaczej i jeśli chcesz wykonać dodatkową pracę z listami, Streams dostarczy Ci więcej alternatyw (filtr, Mapa, redukcja, itp.)

List<String> listA = Stream.of("a", "B", "C").collect(Collectors.toList());
List<Integer> listB = IntStream.range(10, 20).boxed().collect(Collectors.toList());
List<Double> listC = DoubleStream.generate(() -> { return new Random().nextDouble(); }).limit(10).boxed().collect(Collectors.toList());
LinkedList<Integer> listD = Stream.iterate(0, x -> x++).limit(10).collect(Collectors.toCollection(LinkedList::new));
 6
Author: yamilmedina,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-30 14:51:20

W Javie 9 możesz wykonać następujące czynności, aby utworzyć niezmienny List:

List<Integer> immutableList = List.of(1, 2, 3, 4, 5);

List<Integer> mutableList = new ArrayList<>(immutableList);
 6
Author: Jacob G.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-28 00:20:46

Istnieje wiele sposobów tworzenia zestawu i listy. HashSet i ArrayList to tylko dwa przykłady. W dzisiejszych czasach dość powszechne jest również stosowanie leków generycznych ze zbiorami. Proponuję rzucić okiem na to, czym one są

Jest to dobre wprowadzenie do wbudowanych kolekcji Javy. http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html

 5
Author: Peter Lawrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-13 20:01:35
List arrList = new ArrayList();

Lepiej używać leków generycznych, jak sugerowano poniżej:

List<String> arrList = new ArrayList<String>();

arrList.add("one");

Incase you use LinkedList.

List<String> lnkList = new LinkedList<String>();
 5
Author: Rohit Goyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-03 12:52:52

Oto kilka sposobów tworzenia list.

  • Spowoduje to utworzenie listy o stałym rozmiarze, dodanie / usunięcie elementów nie jest możliwe, rzuci java.lang.UnsupportedOperationException jeśli spróbujesz to zrobić.

    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
    


  • Poniższa wersja to prosta lista, na której można dodać/usunąć dowolną liczbę elementów.

    List<String> list = new ArrayList<>();
    


  • Oto jak utworzyć LinkedList w Javie, jeśli trzeba robić częste wstawianie / usuwanie elementów na liście, należy użyć LinkedList zamiast ArrayList

    List<String> linkedList = new LinkedList<>();
    
 5
Author: J J,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-11 11:46:37

Używając Kolekcje Eclipse możesz utworzyć taką listę:

List<String> list1 = Lists.mutable.empty();
List<String> list2 = Lists.mutable.of("One", "Two", "Three");

Jeśli chcesz mieć niezmienną listę:

ImmutableList<String> list3 = Lists.immutable.empty();
ImmutableList<String> list4 = Lists.immutable.of("One", "Two", "Three");

Możesz uniknąć auto-boksu używając prymitywnych list. Oto jak tworzysz listy int:

MutableIntList list5 = IntLists.mutable.empty();
MutableIntList list6 = IntLists.mutable.of(1, 2, 3);

ImmutableIntList list7 = IntLists.immutable.empty();
ImmutableIntList list8 = IntLists.immutable.of(1, 2, 3);

Istnieją warianty dla wszystkich 8 prymitywów.

MutableLongList longList       = LongLists.mutable.of(1L, 2L, 3L);
MutableCharList charList       = CharLists.mutable.of('a', 'b', 'c');
MutableShortList shortList     = ShortLists.mutable.of((short) 1, (short) 2, (short) 3);
MutableByteList byteList       = ByteLists.mutable.of((byte) 1, (byte) 2, (byte) 3);
MutableBooleanList booleanList = BooleanLists.mutable.of(true, false);
MutableFloatList floatList     = FloatLists.mutable.of(1.0f, 2.0f, 3.0f);
MutableDoubleList doubleList   = DoubleLists.mutable.of(1.0, 2.0, 3.0);

Notatka: jestem committerem Dla Kolekcji Eclipse.

 4
Author: Craig P. Motlin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-13 20:37:16

Jako deklaracja listy tablic w Javie jest jak

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

Istnieje wiele sposobów tworzenia i inicjalizacji listy tablic w Javie.

 1) List list = new ArrayList();

 2) List<type> myList = new ArrayList<>();

 3) List<type> myList = new ArrayList<type>();

 4) Using Utility class

    List<Integer> list = Arrays.asList(8, 4);
    Collections.unmodifiableList(Arrays.asList("a", "b", "c"));

 5) Using static factory method

    List<Integer> immutableList = List.of(1, 2);


 6) Creation and initializing at a time

    List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});



 Again you can create different types of list. All has their own characteristics

 List a = new ArrayList();
 List b = new LinkedList();
 List c = new Vector(); 
 List d = new Stack(); 
 List e = new CopyOnWriteArrayList();
 4
Author: Mak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-16 06:37:07

Spróbuj tego:

List<String> messages = Arrays.asList("bla1", "bla2", "bla3");

Lub:

List<String> list1 = Lists.mutable.empty(); // Empty
List<String> list2 = Lists.mutable.of("One", "Two", "Three");
 3
Author: Gavriel Cohen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-18 11:50:48

Jeśli potrzebujesz serializowalnej, niezmiennej listy z jednym podmiotem, możesz użyć:

List<String> singList = Collections.singletonList("stackoverlow");
 2
Author: erol yeniaras,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-03 21:26:24