gather
Earlier we introduced the concept of arrays. Both collections and arrays can be mistaken as containers, but the length of the array is fixed, and the length of the collection can be changed, but the stored elements must be elements of reference data types. It is also a few differences from arrays
We have introduced the Arraylist collection earlier, so I won't go into details here. Today we'll take a look at the collection interface
collection interface
The secondary interface is a top-level interface that defines many functions and methods that subclasses can call
public static void main(String[] args) { // TODO Auto-generated method stub Collection<String>coll=new ArrayList<String>(); //add方法 coll.add("1号"); coll.add("2号"); //集合转属组 Object[] arr=coll.toArray(); for(int i=0;i<arr.length;i++){ System.out.println(arr[i]); } coll.remove( "No.2"); // collection element removal method System.out.println(coll.size()); boolean b=coll.contains("No.2"); // Determine whether there is any in the collection This element coll.clear(); // Clear the contents of your container }
This is the method of the collection's collection to array and adding and removing elements. When turning the array, it can only be an array of Object type.
iterator
Iterator interface: its main function is to get the elements in the collection
public static void main(String[] args) { Collection<String>coll=new HashSet<String>(); coll.add( "Little girl" ); coll.add( "You have to study hard" ); coll.add( "You are so old" ); coll.add( "Like a baby" ); // 1. Get the iterator object // Iterator<String>it=coll.iterator(); // while(it.hasNext()){ // String str=it.next(); // System.out.println(str); // } // System.out.println(it.hasNext()); // System.out.println(it.next() ); for (Iterator<String>it= coll.iterator();it.hasNext();){ System.out.println(it.next()); } }
The hasnext method will return a boolean type data to determine whether there are elements in the collection, and then traverse the collection. Two methods are introduced here, for and while