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!

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools
