Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Collection Interface in Java

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to use the Collection interface in Java". The content is simple and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "how to use the Collection interface in Java".

I. Overview of the collection framework

Background: on the one hand, the object-oriented language embodies things in the form of objects, in order to facilitate the operation of multiple objects, it is necessary to store objects, on the other hand, there are some disadvantages in using Array to store objects, and the Java collection is like a container, which can dynamically put the references of multiple objects into the container.

1. Collections and arrays are structures that store multiple data, referred to as Java containers.

Description: storage at this time, mainly refers to memory-level storage, does not involve persistent storage (.txt, .jpg, .avi, database)

two。 The characteristics of the method of storing multiple data in arrays:

> once initialized, its length is determined.

Once the array is defined, the type of its elements is determined. We can only manipulate the specified type of data.

For example: String [] arr;int [] arr1;Object [] arr2 (polymorphism: data of subclass types can also be stored in arrays (String, etc.))

3. Disadvantages of arrays in storing multiple data:

> once initialized, its length cannot be modified.

The methods provided in the array are very limited, which are very inconvenient and inefficient for operations such as adding, deleting, inserting arrays, etc.

Requirements for getting the actual number of elements in an array, which has no ready-made attributes or methods available

> the characteristics of array data storage: orderly and repeatable. For disordered and unrepeatable requirements, can not be met

2. Collection framework (Java collections can be divided into Collection and Map systems)

A. Collection interface: a single-column collection that is used to store objects one by one

A.List interface: stores orderly and repeatable data. -> dynamic array

| |-ArrayList, LinkedList, Vector |

B.Set interface: storing unordered and non-repeatable data-> "collection" in high school

| |-HashSet, LinkedHashSet, TreeSet |

B. Map interface: double column set, used to store a pair of (key-value) pair of data-> high school function: y = f (x)

| |-HashMap, LinkedHashMap, TreeMap, Hashable, Properties |

Third, the use of methods in the Collection interface

Public void test1 () {Collection coll = new ArrayList (); / / add (Object e): add element e to the collection coll coll.add ("AA"); coll.add ("BB"); coll.add (123); / / Autoboxing coll.add (new Date ()) / / size (): get the number of elements added System.out.println (coll.size ()); / / 4 / / addAll (Collection coll1): add elements from the coll1 collection to the current collection Collection coll1 = new ArrayList (); coll1.add (456); coll1.add ("CC"); coll.addAll (coll1) System.out.println (coll.size ()); / / 6 System.out.println (coll); / / clear (): clear the collection element (the object is still there, but the element is gone) coll.clear (); / / isEmpty (): determine whether the current collection is empty System.out.println (coll.isEmpty ()) } / / conclusion: when adding data obj to the object of the implementation class of the Collection interface, the class where obj belongs is required to override equals (). Public void test2 () {Collection coll = new ArrayList (); coll.add (123); coll.add (456); coll.add (new Person ("Jerry", 20)); coll.add (new String ("Tom")); coll.add (false) / / 1.contains (Object obj): determine whether the current collection contains obj / / We will call equals () boolean contains = coll.contains (123); System.out.println (contains); System.out.println (coll.contains ("Tom")); / / true System.out.println (coll.contains (new Person ("Jerry", 20)) of the class where the obj object is located. / / false-- > ture / / 2.containsAll (Collection coll1): determine whether all elements in the parameter coll1 exist in the current collection Collection coll1 = Arrays.asList (123456); System.out.println (coll.containsAll (coll1));}

Public void test3 () {/ / 3.remove (Object obj): remove the obj element Collection coll = new ArrayList (); coll.add (123); coll.add (456); coll.add (new Person ("Jerry", 20)); coll.add (new String ("Tom")); coll.add (false); coll.remove (1234) from the current collection System.out.println (coll); / / [123Power456, Person {name='Jerry', age=20}, Tom, false] coll.remove (new Person ("Jerry", 20)); System.out.println (coll); / / [123Magne456, Tom, false] / / 4.removeAll (Collection coll1): / / remove all elements in coll1 from the current collection Collection coll1 = Arrays.asList (123ju4567) Coll.removeAll (coll1); System.out.println (coll); / / [456, Tom, false]} public void test4 () {Collection coll = new ArrayList (); coll.add (123); coll.add (456); coll.add (new Person ("Jerry", 20)); coll.add (new String ("Tom")); coll.add (false) / / 5.retainAll (Collection coll1): gets the intersection of the previous collection and the coll1 collection and returns it to the current collection / / Collection coll1 = Arrays.asList (123.456789); / / coll.retainAll (coll1); / / System.out.println (coll) / / 6.equals (Object obj): to return true, you need the same elements of the current collection and the formal parameter collection Collection coll1 = new ArrayList (); coll1.add (123); coll1.add (456); coll1.add (new Person ("Jerry", 20)); coll1.add (new String ("Tom")); coll1.add (false) System.out.println (coll.equals (coll1)); / / true} public void test5 () {Collection coll = new ArrayList (); coll.add (123,456); coll.add (new Person ("Jerry", 20)); coll.add (new String ("Tom")); coll.add (false) / / 7.hashCode (): returns the hash value of the current object System.out.println (coll.hashCode ()); / / 8. Collection-- > Array: toArray () Object [] arr = coll.toArray (); for (int I = 0 Tinci

< arr.length;i++){ System.out.println(arr[i]); } //拓展:数组 -->

Collection: call static methods of Arrays class asList () List list = Arrays.asList (new String [] {"AA", "BB", "CC"}); System.out.println (list); List arr1 = Arrays.asList (new int [] {123,456}); System.out.println (arr1.size ()); / / 1 List arr2 = Arrays.asList (new Integer [] {123,456}) System.out.println (arr2.size ()); / / 2} IV. Traversal operation of set elements A. Use the (iterator) Iterator interface

1. Internal methods: hasNext () and next ()

two。 Each time the collection object calls the iterator () method, it gets a brand new iterator object, with the default cursor before the first element of the collection.

3. Remove () is defined internally. You can delete elements in the collection when traversing, unlike when the collection calls remove () directly.

Note: it.hasNext () must be called for detection before calling the it.next () method. If it is not called and the next record is invalid, calling it.next () directly will throw a NoSuchEiementException exception.

Public class IteratorTest {@ Test public void test1 () {Collection coll = new ArrayList (); coll.add (123); coll.add (456); coll.add (new Person ("Jerry", 20); coll.add (new String ("Tom")); coll.add (false); Iterator iterator = coll.iterator () / / method 1: not recommended / / System.out.println (iterator.next ()); / / System.out.println (iterator.next ()) / / report exception: NoSuchElementException// System.out.println (iterator.next ()); / / method 2: do not recommend / / for (int I = 0

< coll.size();i++){// System.out.println(iterator.next());// } //方式三:推荐 //hasNext():判断是否还有下一个元素 while (iterator.hasNext()){ //next():A 指针下移 B 将下移以后集合位置上的元素返回 System.out.println(iterator.next()); } } @Test public void test2(){ Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new Person("Jerry",20)); coll.add(new String("Tom")); coll.add(false); //错误方式一:// Iterator iterator = coll.iterator();// while((iterator.next()) != null){// System.out.println(iterator.next());//456 Tom//跳着输出// }//还会报异常:NoSuchElementException //错误方式二: //集合对象每次调用iterator()方法都得到一个全新的迭代器对象,默认游标都在集合的第一个元素之前。// while(coll.iterator().hasNext()){// System.out.println(coll.iterator().next());//123死循环// } } //测试Iterator中的remove() @Test public void test3(){ Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new Person("Jerry",20)); coll.add(new String("Tom")); coll.add(false); //删除集合中的"Tom" Iterator iterator = coll.iterator(); while(iterator.hasNext()){ Object obj = iterator.next(); if("Tom".equals(obj)){ iterator.remove(); } } //遍历集合 iterator = coll.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }} B. jdk5.0新增foreach循环,用于遍历集合、数组 @Test//访问Collection public void test1(){ Collection coll = new ArrayList(); coll.add(123); coll.add(456); coll.add(new Person("Jerry",20)); coll.add(new String("Tom")); coll.add(false); //for(集合元素的类型 局部变量:集合对象) //内部仍然调用了迭代器 for(Object obj : coll){ System.out.println(obj); } } @Test//访问数组 public void test2(){ int[] arr = new int[]{1,3,4,5,6}; //for(数组元素的类型 局部变量:数组对象) for(int i : arr){ System.out.println(i); } } 一道笔试题 //笔试题 @Test public void test3(){ String[] arr = new String[]{"MM","MM","MM"}; //方式一:普通for赋值//输出:GG//拿着数组修改,数组存储在堆中,可修改// for(int i = 0;i < arr.length;i++){// arr[i] = "GG";// } //方式二:增强for循环//输出:MM//将数组中的元素一个个赋给字符型变量s,而s存储在常量区,不可被修改 for(String s : arr){ s = "GG"; } for(int i = 0;i < arr.length;i++){ System.out.println(arr[i]); } }五、Collection子接口之一:List接口 简介:鉴于Java中数组用来存储数据的局限性,我们通过使用List代替数组 List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。 List容器中的元素都对应一个整型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。 List接口方法 public void test1(){ ArrayList list = new ArrayList(); list.add(123); list.add(456); list.add("AA"); list.add(new Person("Jerry",20)); list.add(456); System.out.println(list);//[123, 456, AA, Person{name='Jerry', age=20}, 456] //void add(int index,Object ele):在index位置插入ele元素 list.add(1,"BB"); System.out.println(list);//[123, BB, 456, AA, Person{name='Jerry', age=20}, 456] //boolean addAll(int index,Collection eles):从index位置上开始将eles中的所有元素添加进来 List list1 = Arrays.asList(1,2,3); list.addAll(list1); System.out.println(list.size());//9 //Object get(int index):获取指定index位置的元素 System.out.println(list.get(0));//123 } public void test2(){ ArrayList list = new ArrayList(); list.add(123); list.add(456); list.add("AA"); list.add(new Person("Jerry",20)); list.add(456); //int indexOf(Object obj):返回obj在集合中首次出现的位置,如果不存在,返回-1 int index = list.indexOf(4567); System.out.println(index);//-1 //int LastIndexOf(Object obj):返回obj在当前集合中末次出现的位置 System.out.println(list.lastIndexOf(456));//4 //Object remove(int index):移除指定index位置的元素,并返回此元素 Object obj = list.remove(0);//123 System.out.println(list);//[456, AA, Person{name='Jerry', age=20}, 456] //Object set(int index,Object ele):设置指定index位置的元素为ele list.set(1,"CC");//[456, CC, Person{name='Jerry', age=20}, 456] System.out.println(list); // //List subList(int formIndex,int toIndex):返回从formIndex到toIndex位置的左闭右开的子集合 List subList = list.subList(2,4); System.out.println(subList);//[Person{name='Jerry', age=20}, 456] System.out.println(list);//[456, AA, Person{name='Jerry', age=20}, 456] } 遍历List的方式 public void test3(){ ArrayList list = new ArrayList(); list.add(123); list.add(456); list.add("AA"); //方式一:Iterator迭代器的方式 Iterator iterator = list.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } //方式二:增强for循环 for(Object obj : list){ System.out.println(obj); } //方式三:普通for循环 for(int i = 0;i < list.size();i++){ System.out.println(list.get(i)); } 区分List中remove(int index)和remove(Object obj) @Test public void test4(){ ArrayList list = new ArrayList(); list.add(1); list.add(2); list.add(3); updateList(list); System.out.println(list); } public static void updateList(List list){ list.remove(2);//[1, 2]//删掉角标为2的元素 list.remove(new Integer(2));//删掉字符2 } 面试题:ArrayList、LinkedList、Vector三者的异同? 同:三个类都是实现了List接口,存储数据的特点相同:存储有序的、可重复的数据 不同: |---ArrayList:作为List接口的主要实现类:线程不安全的,效率高;底层使用Object[] elementData存储 |---LinkedList:对于频繁的插入、删除操作,使用此类效率比ArrayList高;底层使用双向链表存 储 |---Vector:作为List接口的古老的实现类;线程安全的,效率低;底层使用Object[] elementData存储 ArrayList的源码分析: JDK 7情况下: ArrayList list = new ArrayList();//底层创建了长度是10的Object[]数组elementData list.add(123);//elementData[0] = new Integer(123); ... List.add(11);//如果此次的添加导致底层elementData数组容量不够,则扩容。 默认情况下,扩容为原来的容量的1.5倍,同时需要将原有的数组中的数据复制到新的数组中。 结论:建议开发中使用带参的构造器:ArrayList list = new ArrayList(int capacity) JDK 8中ArrayList的变化: ArrayList list = new ArrayList();//底层Object[] elementData初始化为{}.并没有创建长度为10的数组 list.add(123);//第一次使用add()时,底层才创建了长度为10的数组,并将数据123添加到elementData[0] 后续的添加和扩容操作与JDK 7相同 小结:jdk7中的ArrayList的对象的创建类似于单例的饿汉式,而jdk8中的ArrayList的对象的创建类似于单例的懒汉式,延迟了数组的创建,节省内存 LinkedList的源码分析: LinkedList list = new LinkedList();内部没有声明数组,而是声明了Node类型的first和last属性,默认值为null list.add(123);//将123封装到Node中,创建了Node对象。 其中,Node定义为:体现了LinkedList的双向链表的说法 private static class Node{ E item; Node next;//变量记录下一个元素的位置 Node prev;//变量记录前一个元素的位置 Node(Node prev,E element,Node next){ this.item = element; this.next = next; this.prev = prev; }} Vector的源码分析: jdk7和jdk8中通过Vector()构造器创建对象时,底层都创建了长度为10的数组在扩容方面,默认扩容为原来的数组长度的2倍。 六、Collection子接口之一:Set接口一、Set接口概述 >

The Set interface is a subinterface of Collection, and the set interface provides no additional methods

> the Set collection is not allowed to contain the same elements. If you try to add two identical elements to the same Set collection, the add operation fails.

Set determines whether two objects are the same not by using the = = operator, but by the equals () method

> Note:

There are no additional new methods defined in the 1.Set interface, using methods declared in Collection.

two。 Requirement: the class in which the data is added to Set must override hashCode () and equals ()

Requirement: the rewritten hashCode () and equals () should be as consistent as possible: equal objects must have equal sequence codes.

A tip for rewriting two methods: the Field in the object used as the comparison of the equals () method should be used to calculate the hashcode value

Second, the framework of set interface:

Collection interface: a single-column collection used to store objects one by one

> Set interface: storing unordered and non-repeatable data-> "Collection" in high school

A.HashSet: as the main implementation class of the Set interface: thread unsafe, can store null values

B.LinkedHashSet: as a subclass of HashSet: when traversing its internal data, it can traverse in the order in which it is added

For frequent traversal operations, LinkedHashSet is more efficient than HashSet.

C.TreeSet: can be sorted by the specified properties of the added object

3. Three implementation classes of Set

Rewrite the basic principles of the hashCode () method

When the program is running, the same object should return the same value by calling the hashCode () method multiple times.

When the equals () method comparison of two objects returns true, the return value of the hashCode () method of the two objects should also be equal

The Field in the object that is used to compare the equals () method should be used to calculate the hashcode value.

Public void test1 () {HashSet set = new HashSet (); set.add (456); set.add (123); set.add (123); set.add ("AA"); set.add ("CC"); set.add (new User ("Tom", 12)); set.add (new User ("Tom", 12); set.add (129) Iterator iterator = set.iterator (); while (iterator.hasNext ()) {System.out.println (iterator.next ()); / / AA// CC// 129Accord / 456Accord / 123Compact / User {name='Tom', age=12}}

Set: storing unordered, non-repeatable data

Take HashSet as an example to illustrate:

1. Disorder: not equal to randomness. The stored data is not added in the underlying array in the order of the array index, but is determined by the hash value of the data.

two。 Non-repeatability: make sure that true is not returned when the added element is judged according to equals (). That is, only one element is added to the same element

2. The process of adding elements: take HashSet as an example:

To add element a to HashSet, we first call the hashCode () method of the class where element a belongs to, and calculate the hash value of element a, which is then passed through the

Some algorithm calculates the location (that is, the index location) in the underlying array of HashSet to determine whether there are already elements at this location:

If there are no other elements at this location, element an is added successfully. -- > case 1

If there are other elements b at this position (or multiple elements that exist in the form of a linked list), the as values of element an and element b are compared.

If the hash value is different, the element an is added successfully. -- > case 2

If the hash value is the same, then you need to call the equals () method of the class where element an is located:

Equals () returned true, element a failed to be added

If equals () returns false, the element an is added successfully. -case 3

For cases 2 and 3 where the addition is successful, element an is stored as a linked list with data at the specified index location that already exists.

JDK 7: element an is placed in an array and points to the original element.

LDK 8: the original element is in the array, pointing to element a

Summary: seven up and eight down

HashSet underlying: array + linked list structure (premise: before JDK 7)

The use of LinkedHashSet

LinkedHashSet as a subclass of HashSet, while adding data, each data also maintains two references to record the former data and the latter data.

Advantages: for frequent traversal operations, LinkedHashSet is more efficient than HashSet

Public void test2 () {HashSet set = new LinkedHashSet (); set.add (456); set.add (123); set.add (123); set.add ("AA"); set.add ("CC"); set.add (new User ("Tom", 12)); set.add (new User ("Tom", 12); set.add (129) Iterator iterator = set.iterator (); while (iterator.hasNext ()) {System.out.println (iterator.next ());}}

Note:

1. The data added to the TreeSet requires similar objects.

two。 Two sorting methods: natural sorting (implementing Comparable interface) and custom sorting (Comparator)

3. In natural sorting, the criterion for comparing whether two objects are the same is: compareTo () returns 0. 0. It is no longer equals ().

In custom sorting, the criterion for comparing whether two objects are the same is: compare () returns 0. 0. It is no longer equals ().

4.TreeSet and TreeMap to be discussed later adopt the storage structure of red-black tree; features: orderly, faster query speed than List

Public void test1 () {TreeSet set = new TreeSet (); / / error: ClassCastException cannot add objects of different classes / / set.add (123); / / set.add (456); / / set.add ("AA"); / / set.add (new User ("Tom", 12)); / / example 1: / / set.add (34) / / set.add (- 34); / set.add (43); / / set.add (11); / / set.add (8); / / example II: set.add (new User ("Tom", 12)); set.add (new User ("Jerry", 32)); set.add (new User ("Jim", 2)) Set.add (new User ("Mike", 65)); set.add (new User ("Jack", 22)); set.add (new User ("Jack", 62)); Iterator iterator = set.iterator (); while (iterator.hasNext ()) {System.out.println (iterator.next ()) } @ Test public void test2 () {Comparator com = new Comparator () {@ Override public int compare (Object o1, Object O2) {if (o1 instanceof User & & O2 instanceof User) {User U1 = (User) o1; User U2 = (User) O2 Return Integer.compare (u1.getAge (), u2.getAge ());} else {throw new RuntimeException ("input type mismatch");}; TreeSet set = new TreeSet (com); set.add (new User ("Tom", 12)) Set.add (new User ("Jerry", 32)); set.add (new User ("Jim", 22)); set.add (new User ("Mike", 65)); set.add (new User ("Jack", 22)); set.add (new User ("Jack", 62)); Iterator iterator = set.iterator () While (iterator.hasNext ()) {System.out.println (iterator.next ());}} these are all the contents of the article "how to use the Collection Interface in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report