2417

Вопрос по java – Инициализация ArrayList в одну строку

Error: User Rate Limit Exceeded

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Затем я изменил код следующим образом:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Error: User Rate Limit Exceeded

  • Error: User Rate Limit ExceededArrays.asListError: User Rate Limit Exceededdocs.oracle.com/javase/1.5.0/docs/guide/language/…

    от
  • Error: User Rate Limit ExceededasList(...)Error: User Rate Limit ExceededListError: User Rate Limit ExceededremoveError: User Rate Limit ExceededclearError: User Rate Limit ExceededListError: User Rate Limit ExceededListError: User Rate Limit ExceededList l = new ArrayList(asList(...))Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededArrayListError: User Rate Limit ExceededListError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededdependingError: User Rate Limit ExceededremoveError: User Rate Limit ExceededmeaningfulError: User Rate Limit ExceededintentError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededremoveError: User Rate Limit ExceededclearError: User Rate Limit ExceededListError: User Rate Limit ExceededasList(...)Error: User Rate Limit ExceededLi,stError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededstackoverflow.com/questions/924285Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededdocs.oracle.com/javase/9/docs/api/java/util/List.html#of-E...-

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededone lineError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededadd()Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededListError: User Rate Limit ExceededList<String> places = Arrays.asList(...);Error: User Rate Limit Exceededplaces.add("blabla")

    от
  • Error: User Rate Limit Exceedednot the same class.

    от
  • Error: User Rate Limit ExceededcanError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededjava.util.ArraysError: User Rate Limit ExceededList<String> names = Arrays.asList("Beckah", "Sam", "Michael");

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededObject.

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededstackoverflow.com/a/924326/760393

    от
  • Error: User Rate Limit Exceededletters = Arrays.asList(new String[]{"A", "B", "C"});

    от
  • Error: User Rate Limit ExceededImmutableListError: User Rate Limit ExceededListError: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от Macarse
  • This method is not actually very useful and will likely be deprecated in the future.

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit ExceededCollections.unmodifiableList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"))Error: User Rate Limit ExceededunmodifiableList(asList("Buenos Aires", "Córdoba", "La Plata"))Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceeded

    от
  • Error: User Rate Limit Exceededstackoverflow.com/questions/157944/create-arraylist-from-array

    от Christoffer Hammarström
  • Error: User Rate Limit Exceeded

    от Rose
  • Error: User Rate Limit Exceeded

    от torina
  • Error: User Rate Limit Exceeded

    от Mohammadreza Khatami
  • Error: User Rate Limit ExceededArrasyList<String> places = ["Buenos Aires", "Córdoba", "La Plata"]

    от ripper234
30 ответов
  • 26

    Code:

    import com.google.common.collect.ImmutableList;
    
    ....
    
    List<String> places = ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
    

  • 4

    Code:

    List<String> names = Arrays.asList("2","@2234","21","11");
    

  • 6

    Error: User Rate Limit Exceeded

    Code Snippet:
    String [] arr = {"Sharlock", "Homes", "Watson"};
    
    List<String> names = Arrays.asList(arr);
    

  • 7

    Error: User Rate Limit Exceeded

    List<String> values = Stream.of("One", "Two").collect(Collectors.toList());
    

  • 1

    Error: User Rate Limit Exceeded

    // ArrayList
    List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
    // HashSet
    Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
    // HashMap
    Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
    
    // Or for Immutable List/Set/Map
    ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
    ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
    ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);
    
    // The most efficient way, which is similar with Arrays.asList(...) in JDK. 
    // but returns a flexible-size list backed by the specified array.
    List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");
    

  • 54

    Error: User Rate Limit Exceeded

    ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata");
    

    .

  • 1

    Error: User Rate Limit Exceeded

    package main_package;
    
    import java.util.ArrayList;
    
    
    public class Stackkkk {
        public static void main(String[] args) {
            ArrayList<Object> list = new ArrayList<Object>();
            add(list, "1", "2", "3", "4", "5", "6");
            System.out.println("I added " + list.size() + " element in one line");
        }
    
        public static void add(ArrayList<Object> list,Object...objects){
            for(Object object:objects)
                list.add(object);
        }
    }
    

  • -4

    Error: User Rate Limit Exceeded

    public static <T> List<T> asList(T... a) {
        return new ArrayList<T>(a);
    }
    

    Arrays.asList

    ArrayList<String> arr = (ArrayList<String>) Arrays.asList("1", "2");
    

  • 22

    Error: User Rate Limit Exceeded

    public static ArrayList<String> createArrayList(String ... elements) {
      ArrayList<String> list = new ArrayList<String>();
      for (String element : elements) {
        list.add(element);
      }
      return list;
    }
    
    ....
    
    ArrayList<String> places = createArrayList(
      "São Paulo", "Rio de Janeiro", "Brasília");
    

    public static <T> ArrayList<T> createArrayList(T ... elements) {
      ArrayList<T> list = new ArrayList<T>();
      for (T element : elements) {
        list.add(element);
      }
      return list;
    }
    

  • 3

    Error: User Rate Limit Exceeded

    List<String> strlist= Arrays.asList("aaa", "bbb", "ccc");
    

  • -1

    Error: User Rate Limit Exceeded

    Arrays.asList(new MyClass[] {new MyClass("arg1"), new MyClass("arg2")})
    

  • 1

    Error: User Rate Limit Exceeded

    Collections.singletonList(messageBody)
    

    one item!

    Collectionsjava.util

  • 4

    Error: User Rate Limit Exceeded

    StickyList:

    List<String> names = new StickyList<>(
      "Scott Fitzgerald", "Fyodor Dostoyevsky"
    );
    

  • 7

    Error: User Rate Limit Exceeded

    List<String> list = new ArrayList<String>() {{
                add("A");
                add("B");
                add("C");
    }};
    

  • 7

    Error: User Rate Limit Exceeded

    List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    

    MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");
    

    Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");
    
    Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");
    

    Note:

  • 5

    Error

    User Rate Limit Exceededimmutable: User Rate Limit Exceeded

    List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
    

    : User Rate Limit Exceeded

    List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
    

    : User Rate Limit ExceededSet: User Rate Limit ExceededMap.

  • 3

    Error: User Rate Limit Exceeded Collections.singletonList(provider)

    Error: User Rate Limit Exceeded

    Collections.singletonList(provider)
    

  • 0

    Error: User Rate Limit Exceeded

    static <A> ArrayList<A> ll(A... a) {
      ArrayList l = new ArrayList(a.length);
      for (A x : a) l.add(x);
      return l;
    }
    

    ll

    ArrayList<String> places = ll("Buenos Aires", "Córdoba", "La Plata");
    

  • 0

    Error: User Rate Limit Exceeded

  • 15

    Error: User Rate Limit Exceeded

    ArrayList

    List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");
    

    List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));
    

    Space Efficiency Immutability Thread Safe

  • 1918

    Error: User Rate Limit Exceeded

    List

    List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
    

    List<String> places = Collections.singletonList("Buenos Aires");
    

    placesimmutableUnsupportedOperationException

    ArrayListArrayList

    ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
    

  • 105

    Error: User Rate Limit Exceeded

    List<String> strings = new ArrayList<String>(Collections.singletonList("A"));
    

    List<String> strings = new ArrayList<String>();
    Collections.addAll(strings,"A","B","C","D");
    

  • 31

    Error: User Rate Limit Exceeded

    List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());
    

    ListArrayList:

    ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));
    

  • 23

    Error: User Rate Limit Exceeded

    Java 9collection literals

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

    Map

    Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")
    

    Alternatives

    Language changes have been considered several times, and rejected:

    Project Coin Proposal, 29 March 2009

    Project Coin Proposal, 30 March 2009

    JEP 186 discussion on lambda-dev, January-March 2014

    The language proposals were set aside in preference to a library-based proposal as summarized in this message.

  • 7

    Error: User Rate Limit Exceeded

    Double array[] = { 1.0, 2.0, 3.0};
    List<Double> list = Arrays.asList(array);
    

  • 5

    Error: User Rate Limit Exceeded

    :

    List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
    

    ArrayList<String> myPlaces = new ArrayList(places);
    

    String[] places = {"Buenos Aires", "Córdoba", "La Plata"};
    

    ArrayList<String> myPlaces = new ArrayList(Arrays.asList(places));
    

    enum

    enum Places {BUENOS_AIRES, CORDOBA, LA_PLATA}
    

    enum Places {
        BUENOS_AIRES("Buenos Aires",123),
        CORDOBA("Córdoba",456),
        LA_PLATA("La Plata",789);
    
        String name;
        int code;
        Places(String name, int code) {
          this.name=name;
          this.code=code;
        }
    }
    

    values

    for (Places p:Places.values()) {
        System.out.printf("The place %s has code %d%n",
                      p.name, p.code);
    }
    

    .

  • 2

    Error: User Rate Limit Exceeded

    ArrayList<String> places = new ArrayList<String>( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
    

    List<String> places = new ArrayList<String>() {{ add("x"); add("y"); }};
    

    @SuppressWarnings("serial")

    List<String> places = Arrays.asList(new String[] {"x", "y" });
    

    @SuppressWarnings("unchecked").

    List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
    

  • 6

    Error: User Rate Limit Exceeded

    Arrays.asList

    class A{}
    class B extends A{}
    
    public List<A> getAList(){
        return Arrays.asList(new B());
    }
    

    List<B>List<A>List<A>

    new ArrayList<A>(Arrays.<A>asList(b1, b2, b3))
    

  • 715

    Error: User Rate Limit Exceeded

    The simple answer

    var strings = List.of("foo", "bar", "baz");
    

    List<String> strings = List.of("foo", "bar", "baz");
    

    List

    Java 8 or earlier:
    List<String> strings = Arrays.asList("foo", "bar", "baz");
    

    List
    List.set

    Arrays.asList

    List<String> strings = asList("foo", "bar", "baz");
    

    import static java.util.Arrays.asList;  
    


    Alt+EnterStatic import method....

    List.ofof
    List.of

    Using Streams

    List?
    Stream

    Stream<String> strings = Stream.of("foo", "bar", "baz");
    

    Stream

    Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),
                                           Stream.of("baz", "qux"));
    

    StreamList:

    List<String> strings = Stream.of("foo", "bar", "baz").collect(toList());
    

    StreamList.

    If you really specifically need a java.util.ArrayList


    There is a small set of use cases for initializing a mutable collection instance with a predefined set of values. It's usually preferable to have those predefined values be in an immutable collection, and then to initialize the mutable collection via a copy constructor.

    bothArrayList and

    ArrayList<String> strings = new ArrayList<>(List.of("foo", "bar"));
    strings.add("baz");
    

    ArrayList<String> strings = new ArrayList<>(asList("foo", "bar"));
    strings.add("baz");
    

    Stream:

    ArrayList<String> strings = Stream.of("foo", "bar")
                                 .collect(toCollection(ArrayList::new));
    strings.add("baz");
    

    StreamList.

    Program to interfaces, not to implementations

    ArrayListArrayListList.

    Iterable, CollectionListArrayList, LinkedListArrays.asList()).

    ArrayListvoid method(...):

    // Iterable if you just need iteration, for (String s : strings):
    void method(Iterable<String> strings) { 
        for (String s : strings) { ... } 
    }
    
    // Collection if you also need .size(), .isEmpty(), or .stream():
    void method(Collection<String> strings) {
        if (!strings.isEmpty()) { strings.stream()... }
    }
    
    // List if you also need .get(index):
    void method(List<String> strings) {
        strings.get(...)
    }
    
    // Don't declare a specific list implementation
    // unless you're sure you need it:
    void method(ArrayList<String> strings) {
        ??? // You don't want to limit yourself to just ArrayList
    }
    

    InputStreamFileInputStreamBufferedInputStreamInputStream.

  • 1790

    Error: User Rate Limit Exceeded

    ArrayListList

    ArrayList<String> list = new ArrayList<String>();
    list.add("A");
    list.add("B");
    list.add("C");
    

    list

    ArrayList<String> list = new ArrayList<String>() {{
        add("A");
        add("B");
        add("C");
    }};
    

    ArrayList

    List<String> list = ["A", "B", "C"];
    

    ListArrayList