Overview:
1, Collection definition: inherits Iterable, has generic functions, and is the top parent interface of the Collection collection system.
2, Collection methods: add, addAll; clear, isEmpty, size; toArray (overloaded); iterator; contains, containsAll; remove, removeAll, retainAll;
First, let’s take a look at the definition of Collection
<span style="color: #cc7832">public interface CollectionE> <span style="color: #cc7832">extends IterableE><br><span style="color: #000000">从定义中我们可以看出Collection是一个带<span style="color: #ff0000">泛型的接口</span>。<br>实现了Iterable接口,也就是说可以使用<span style="color: #ff0000">迭代</span>器。<br>以上两点很重要,其下所有子类均有这两个属性。<br>还有一点大家需要注意Collection集合并<span style="color: #ff0000">没有定义查找</span>的方法。<br><br></span></span></span>
Second, let’s take a look at Colleciton own methods (excluding inherited methods).
#1, about add and addAll.
Both add elements to the collection (their respective subclasses will implement it specifically).
The former is to add a single element, and the latter is to add a subclass collection that implements Collection.
For example (I deliberately used different Collection subclasses in the example):
<br>
@Testpublic void testAdd(){ Collection<string> collection = new LinkedList();//添加一个对象collection.add("person1"); collection.add("person2"); List<string> list = new ArrayList(); list.add("person3"); Set<string> set = new HashSet(); set.add("person4");//添加一个Collection集合。 collection.addAll(list); collection.addAll(set); collection.forEach(System.out::println);//打印控制台 }</string></string></string>
2, clear, isEmpty, size.
These methods are relatively simple and crude, so I put them together, and I won’t show the code by the way.
clear clears all elements in the collection.
isEmpty determines whether there are any elements in the collection and returns true when it is empty.
size gets the number of elements in the collection.
3, about converting a collection into an array toArray.
ToArray overloaded method, one has no parameters, and a number needs to be passed in an existing array.
Let’s first talk about Object[] toArray() without parameters. It returns an Object array, so here comes the problem.
If you need String[] objects = (String[]) collection.toArray(); When doing this, it will throw a ClassCastException exception.
Then you may know what
The following code prints the following results, which means that array objects will be returned in any case.
When the length of the passed array is less than the size of the collection, a new array will be returned separately, and the passed array will not be filled with data.
When the passed array is equal to or greater than the combined size, the incoming array is filled and the array is returned.
Note: Therefore, generally we should use the second case of the method with parameters
---Print the situation when the given array is smaller than the set-----<br>strings: [null, null]<br>returnStrings: [escore, wym, cl]<br>strings==returnStrings: false<br>---Print the case when the given array is equal to the set-----<br>strings: [escore, wym, cl]<br>returnStrings: [escore, wym, cl]<br>strings==returnStrings: true<br>---Print the case when the given array is larger than the set--- --<br>strings: [escore, wym, cl, null, null]<br>returnStrings: [escore, wym, cl, null, null]<br>strings==returnStrings: true
Collection<string> collection = new LinkedList(); collection.add("escore"); collection.add("wym"); collection.add("cl"); // String[] objects = (String[]) collection.toArray(); //会抛出ClassCastException异常Object[] objects = collection.toArray();//System.out.println(Arrays.toString(objects));String[] strings = new String[2]; String[] returnStrings = collection.toArray(strings); System.out.println("---打印给定的数组小于集合的情况-----"); System.out.println("strings: "+ Arrays.toString(strings)); System.out.println("returnStrings: " + Arrays.toString(returnStrings)); System.out.println(strings == returnStrings); String[] strings2 = new String[collection.size()]; String[] returnStrings2 = collection.toArray(strings2); System.out.println("---打印给定的数组等于集合的情况-----"); System.out.println("strings: "+ Arrays.toString(strings2)); System.out.println("returnStrings: " + Arrays.toString(returnStrings2)); System.out.println(strings2 == returnStrings2); String[] strings3 = new String[5]; String[] returnStrings3 = collection.toArray(strings3); System.out.println("---打印给定的数组大于集合的情况-----"); System.out.println("strings: "+ Arrays.toString(strings3)); System.out.println("returnStrings: " + Arrays.toString(returnStrings3)); System.out.println(strings3 == returnStrings3);</string>
4IteratorE> iterator()
About return We will not discuss the method of an iterator here. Please refer to the content excuse of Iterator.
5, contains, containsAll; remove, removeAll, retainAll
contains, and containsAll are respectively used to determine whether it contains an allicin , whether it contains a Collection collection.
remove, removeAll, and retainAll respectively delete an element in the collection, delete elements equal to the Collection collection, and retain elements equal to the elements in the Collection collection.
Why put these together?
The equals method is involved here;
That is to say, how does contains determine whether it is included? This method will compare the equals method of the incoming object with the elements in the collection one by one. are equal. The containsAll method will put each element to call the contains method.
Similarly, why remove knows which element needs to be deleted, and will also call the equals method to compare it with the elements in the collection one by one. RemoveAll and retainAll will cause the incoming collection elements to call the remove method one by one, except that the former deletes the same ones, and the latter retains the same ones.
(I will share all about Java collections in the category of "Java Basic Collection Framework")
The above is the detailed content of Detailed introduction to Colleciton in Java. For more information, please follow other related articles on the PHP Chinese website!

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
