java collections

await 2021-09-15 09:58:24

ava Of java.util The package mainly provides the following three types of collections :

{collapse-item label="list" open}

{tabs-pane label="list Iterator Traversal cycle "}

//1 list Ordered set
List list=new ArrayList<>();
list.add("xiaomi");
list.add("apple");
list.add("apple");
list.add(null);
System.out.println(list.size());
for (int i=0;i

Iterator There are two ways to object : boolean hasNext() Determine if there is the next element , E next() Returns the next element . therefore , Use Iterator Traverse List The code is as follows :

for (Iterator it=list.iterator();it.hasNext();){
System.out.println(it.next());
}
// Abbreviation foreach
for (String s:list){
System.out.println(s);
}

{/tabs-pane}

{tabs-pane label="List Turn into Array Three "}

// Method 1
// call toArray() Method directly returns a Object[] Array
List intlist= List.of(123,456,789);
Object[] arr1=intlist.toArray();
for (Object s:arr1){
System.out.println(s);
}
// Method 2
// It's for toArray(T[]) Pass in a... Of the same type Array,
// List Internally, the elements are automatically copied to the incoming Array in
//new Integer[intlist.size()] Pass in an array of just the size
Integer[] arr2=intlist.toArray(new Integer[intlist.size()]);
for (Integer n:arr2) {
System.out.println(n);
}
// Method 3
// adopt List Interface defined T[] toArray(IntFunction generator) Method
Integer[] arr3=intlist.toArray(Integer[]::new);
for (Integer n:arr3){
System.out.println(n);
}

{/tabs-pane} {tabs-pane label="Array Turn into List"}

//array turn list
//List.of(T...) The method is the simplest
Integer[] array = { 1, 2, 3 };
List interlist = List.of(array);
for (Integer n:interlist){
System.out.println(n);
}

{/tabs-pane}

{/collapse-item} {collapse-item label=" Collapse Title II "} Fold content two {/collapse-item}

This article altogether 352 Number of words , Average reading time ≈ 1 minute

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

Please bring the original link to reprint ,thank
Similar articles

2021-09-15