Home Java javaTutorial Detailed introduction to Colleciton in Java

Detailed introduction to Colleciton in Java

Jun 20, 2017 pm 04:33 PM
java interface gather

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 Collection<<span style="color: #507874">E> <span style="color: #cc7832">extends Iterable<<span style="color: #507874">E><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>
Copy after login

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>
Copy after login
    @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);//打印控制台
    }
Copy after login

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 T[] toArray(T[] a) with parameters is for, see below.

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);
Copy after login

4Iterator<E> 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

What is the difference between an abstract class and an interface in PHP? What is the difference between an abstract class and an interface in PHP? Apr 08, 2025 am 12:08 AM

The main difference between an abstract class and an interface is that an abstract class can contain the implementation of a method, while an interface can only define the signature of a method. 1. Abstract class is defined using abstract keyword, which can contain abstract and concrete methods, suitable for providing default implementations and shared code. 2. The interface is defined using the interface keyword, which only contains method signatures, which is suitable for defining behavioral norms and multiple inheritance.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles