The arrays and collections in the Java.util package provide a number of convenient ways to add elements to and from one collection. Arrays.asList()
method takes an array or a comma-delimited list of elements and converts it to a single List object. Of course, the elements stored in this array or the elements in the list can be any object. Instead Collections.addAll()
, the method takes an collection object and an array, or a comma-delimited list of elements, to add elements to the collection object.
//the collection constructor can accept another collection to initialize itself//arrays.aslist () to generate input for itCollection<integer> Collection =NewArraylist<> (Arrays.aslist (1, 2, 3, 4, 5, 6)); integer[] Moreints= {7, 8, 9, 10,};collection.addall (Arrays.aslist (moreints));//The following is going to run a little faster, but you can't construct a collection in this way.Collections.addall (Collection, 11, 12, 13, 14, 15); Collections.addall (collection, moreints);//creates a list in an array but cannot add elements to it because the array length is fixed.//If you try to add it will result in a run-time error, which means it will only be runlist<integer> list = Arrays.aslist (1, 2, 3, 4, 5);//List.add (6);
Arrays.asList()
And Collections.addAll()
uses a variable parameter list, which is more flexible than the Collection.addAll()
member method.
The thinking Arrays.asList()
in Java section may be a bit out of date, such as when discussing the Arrays.asList()
type of list produced.
classSnow {}classPowderextendsSnow {}classLightextendsPowder {}classHeavyextendsPowder {}classCrustyextendsSnow {}classSlushextendsSnow {} Public classAslistinference { Public Static voidMain (string[] args) {List<Snow> Snow1 =Arrays.aslist (NewCrusty (),NewSlush (),NewPowder ()); //the list that can be compiled will not be powder type but snowList<snow> Snow2 =Arrays.aslist (NewLight (),NewHeavy ()); List<Snow> SNOW3 =NewArraylist<>(); Collections.addall (SNOW3,NewLight (),NewHeavy ()); List<Snow> snow4 = arrays.<snow>Aslist (NewLight (),NewHeavy ()); } }
The above four methods are now available, which snow2
are not compiled before Java8. The fourth way to look at it now seems a bit superfluous, of course you have to use JAVA8.
Java container add Element