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 the Java collection method

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this article "how to use the Java collection method", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use the Java collection method" article.

Java collection

The java collection class is stored in the java.util package and is a container for storing objects

Collections can only store objects

The collection stores references to multiple objects, and the object itself is still stored in heap memory

Collections can store an unlimited number of data types of different types

Set classification-- Set, List and Map

Set: an unordered, unrepeatable set

List: an ordered, repeatable set

Map: collections with mapping relationships

After JDK5, generics have been added, and the java collection can remember the data types of objects in the container

SetHashSet

The order of elements cannot be guaranteed (the position is determined by the hashcode of the value)

Non-repeatable (means that the hashcode is different)

HashSet is not thread safe

Collection elements can be stored in null

The HashSet class implements the set interface and the set interface inherits the Collection interface

HashCode () method

The criteria by which the HashSet set determines the equality of two elements: two objects are compared to be equal by the equals () method, and the hashCode () method returns the same value for the two objects.

If two objects return true through the equals () method, the hashCode values of the two objects should also be the same.

Use generics if you want the set collection to store objects of the same type

Package com.aggregate.demo;import com.sun.corba.se.spi.ior.IORTemplateList;import java.util.HashSet;import java.util.Iterator;public class set {public static void main (String [] args) {HashSet set = new HashSet (); set.add (1); set.add ("a"); / / add element System.out.println (set); set.remove (1) / / remove the element System.out.println (set); System.out.println (set.contains ("a")); / / determine whether the element set.clear () exists in the collection; / / clear the collection System.out.println (set); / / traverse the collection set.add ("a"); set.add ("b"); set.add ("c") Set.add ("d") / / 1. Use the iterator to traverse the collection Iterator iterator = set.iterator (); while (iterator.hasNext ()) {System.out.print (iterator.next () + "\ t");} System.out.println ("="); / / 2.for each iterative collection for (Object I: set) {System.out.print (I + "\ t") } System.out.println ("="); System.out.println (set.size ()); / / get the number of elements set.add (null); System.out.println (set); / / use generics to store elements of the same type HashSet set1 = new HashSet (); set1.add ("123"); / / set1.add (2);}} TreeSet

TreeSet is the implementation class of the SortedSet interface, and TreeSet ensures that the collection elements are in a sorted state.

TreeSet supports two sorting methods: natural sorting and custom sorting. By default, TreeSet uses natural sorting

Natural ordering

Sort: TreeSet calls the compareTo (Object obj) method of the collection elements to compare the size relationships between the elements, and then sorts the collection elements in ascending order

How are custom classes sorted?

Import java.util.Comparator;import java.util.Iterator;import java.util.TreeSet;public class Tree {public static void main (String [] args) {TreeSet treeSet = new TreeSet (); / / TreeSet Natural sort treeSet.add (5); treeSet.add (1); treeSet.add (3); treeSet.add (2); treeSet.add (4); System.out.println (treeSet) TreeSet.remove (3); System.out.println (treeSet); System.out.println (treeSet.contains (0)); treeSet.clear (); System.out.println (treeSet); Iterator iterator = treeSet.iterator (); while (iterator.hasNext ()) {System.out.println (iterator.next ());} System.out.println ("=") For (Integer I: treeSet) {System.out.println (I);} Person P1 = new Person (23, "Zhang San"); Person P2 = new Person (25, "Li Si"); Person P3 = new Person (12, "Wang Wu"); Person P4 = new Person (5, "Lucy"); Person P5 = new Person (99, "hhhh") TreeSet people = new TreeSet (new Person ()); people.add (P1); people.add (P2); people.add (P3); people.add (P4); people.add (P5); for (Person I: people) {System.out.println (i.name + "" + i.age) Save person objects to TreeSet and sort class Person implements Comparator {int age; String name; public Person () {} public Person (int age, String name) {this.age = age; this.name = name by age } @ Override public int compare (Person o1, Person O2) {/ / Age positive sort if (o1.age > o2.age) {return 1;} else if (o1.age)

< o2.age) { return -1; } else { return 0; } }}ListList与ArrayList List代表一个元素有序、且可重复的集合,集合中的每个元素都有其对应的顺序索引 List允许使用重复元素,可以通过索引来访问指定位置的集合元素 List默认按元素的添加顺序设置元素的索引 List集合里添加了一些根据索引来操作集合元素的方法 ArrayList和Vector ArrayList和Vector是List接口的两个典型实现 区别: Vector是一个古老的集合,通常建议使用ArrayList ArrayList是线程不安全的,而Vector是线程安全的 即使为保证List集合线程安全,也不推荐使用VectorMap Map 用于保存具有映射关系的数据,因此Map集合里保存着两组值,一组值用于保存Map里key,另外一组用于保存Map里的Value Map中的key和value都可以是任何引用类型的数据 Map中的key不允许重复,即同一个Map对象的任何两个Key通过equals方法比较返回false key和value之间存在单向一对一关系,即通过指定的key总能找到唯一的,确定的Value HashMap & Hashtable HashMap和Hashtable是Map接口的两个典型实现类 区别: Hashtable是一个古老的Map实现类,不建议使用 Hashtable是线程安全的Map实现,但HashMap是线程不安全的 Hashtable不允许使用null作为key和value,而HashMap可以 与HashSet集合不能保证元素的顺序一样,Hashtable、HashMap也不能保证其中key-value对的顺序 Hashtable、HashMap判断两个key的标准是:key通过equals方法返回true,hashCode值也相等 Hashta5ble相等的标准是:两个Value通过equalHashMap判断两个Value方法返回true import java.util.HashMap;import java.util.Map;import java.util.Set;public class MapDemo { public static void main(String[] args) { Map map = new HashMap(); map.put("b", 1);//添加数据 map.put("c", 2); map.put("d", 3); System.out.println(map); System.out.println(map.get("d"));//根据key取值 map.remove("c"); System.out.println(map);//根据key键值对 System.out.println(map.size());//map集合的长度 System.out.println(map.containsKey("a"));//判断当前的map集合是否包含指定的key System.out.println(map.containsValue(10));//判断当前的map集合是否包含指定的value// map.clear();//清空集合 Set keys = map.keySet();//可以获取map集合的key的集合 map.values();//获取集合的所有value值 //遍历map集合,通过map.keySet(); for (String key : keys) { System.out.println("key:" + key + ", value:" + map.get(key)); } //通过map.entrySet();遍历集合 Set entries = map.entrySet(); for (Map.Entry entry : entries) { System.out.println("key:" + entry.getKey() + ", value:" + entry.getValue()); } }}TreeMap TreeMap存储key-value对时,需要根据key对key-value对进行排序。TreeMap可以保证所有的key-value对处于有序状态 TreeMap的key排序 自然排序:TreeMap的所有的key必须实现Comparable接口,而且所有的key应该是同一个类的对象,否则将会抛出ClassCastException 定制排序(了解):创建TreeMap时,传入一个Comparator对象,该对象负责对TreeMap中的所有key排序。此时不需要Map的key实现Comparator接口 import java.util.Map;import java.util.TreeMap;public class TreeMapDemo { public static void main(String[] args) { //TreeMap的自然排序是字典 Map treemap = new TreeMap(); treemap.put(4, "a"); treemap.put(3, "b"); treemap.put(2, "c"); treemap.put(1, "d"); System.out.println(treemap); Map map = new TreeMap(); map.put("a", "a"); map.put("c", "a"); map.put("d", "a"); map.put("b", "a"); map.put("ab", "a"); System.out.println(map); }}操作集合的工具类:Collections Collections是一个操作Set 、List和Map等集合的工具类 Collections中提供了大量方法对集合元素进行排序、查询和修改等操作,还提供了对集合对象设置不可变,对集合对象实现同步控制等方法 排序操作: reverse(List):反转List中元素的顺序 shuffle(List):对List集合元素进行随机排序 sort(List):根据元素的自然顺序对指定List集合元素升序排序 sort(List,Comparator):根据指定的Comparator产生的顺序对List集合元素进行排序s wap(List,int,int):将指定list集合中的i处元素和j处元素进行交换 查找、替换 Object max(Collection):根据元素的自然顺序,返回给定集合中的最大元素 Object max(Collection,Comparator):根据Comparator指定的顺序,返回给定集合中的最大元素 Object min(Collection) Object min(Collection,Comparator) int frequency(Collection,Object):返回指定集合中指定元素的出现次数 boolean replaceAll(List list,Object oldVal,Object newVal):使用新值替换List对象的所有旧值 import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class Test { public static void main(String[] args) { List list = new ArrayList(); list.add("a"); list.add("c"); list.add("d"); list.add("f"); list.add("b"); System.out.println(list); Collections.reverse(list);//反转List中元素的顺序 System.out.println(list); Collections.shuffle(list);//对list集合元素进行顺序排序 System.out.println(list); Collections.sort(list);//list集合字典升序排序 System.out.println(list); Student s1 = new Student(14, "张三"); Student s2 = new Student(12, "李四"); Student s3 = new Student(13, "王五"); Student s4 = new Student(11, "小刘"); List students = new ArrayList(); students.add(s1); students.add(s2); students.add(s3); students.add(s4); for (Student student : students) { System.out.println(student.name + "," + student.age); } Collections.sort(students, new Student()); System.out.println("=========="); for (Student student : students) { System.out.println(student.name + "," + student.age); } Collections.swap(list, 1, 3);//将指定list集合中的i处元素和j处元素进行交换 System.out.println(list); System.out.println(Collections.max(list)); System.out.println(Collections.min(list)); Student max = Collections.max(students, new Student()); Student min = Collections.min(students, new Student()); System.out.println(max.name + ", " + max.age); System.out.println(min.name + ", " + min.age); System.out.println(Collections.frequency(list, "a")); System.out.println(Collections.replaceAll(list, "a", "aa")); System.out.println(list); }}class Student implements Comparator { int age; String name; public Student() { } public Student(int age, String name) { this.age = age; this.name = name; } @Override //根据年龄升序排序对象 public int compare(Student o1, Student o2) { if (o1.age >

O2.age) {return 1;} else if (o1.age < o2.age) {return-1;} else {return 0;}} synchronous control

Multiple synchronizedxxx () methods are provided in the Collections class to wrap a specified collection into a thread-synchronized collection; thus solving thread-safety problems when multithreading and accessing the collection.

Why generics should have generics

When generics are used in a collection, only specified types can be added to the collection. Type safety

Generics in java are only valid at compile time.

Generic class

No generics are specified when the object is instantiated. Default is: object

Different references to generics cannot be assigned to each other

Public class Test2 {public static void main (String [] args) {An a = new A (); a.setKey ("rexx"); String s = a.getKey (); System.out.println (s);}} class A {private T key; public T getKey () {return key;} public void setKey (T key) {this.key = key;}}

Generic interface

Define a generic interface

When the generic argument is not passed in, it is the same as the definition of the generic class. When you declare the class, you need to add the declaration of the generic type to the class.

Generic method

Package com.aggregate.demo;public class Test3 {public static void main (String [] args) {B1 b1 = new B1 (); B1 b2 = new B1 (); B2 b3 = new B2 (); Cc cc = new Cc (); cc.test ("xxx") / / generic method, there is no fixed data type before the call / / the generic method will change the generic type to whatever type is passed in when calling / / that is, the generic method will determine the specific data type of the generic type Integer integer = cc.test1 (2); Boolean aBoolean = cc.test1 (true) }} / / define the generic interface interface IB {T test (T t);} / / when no generic argument is passed, it is the same as the definition of the generic class. When declaring the class, you need to add the declaration of the generic type to the class class B1 implements IB {@ Override public T test (T t) {return null }} / / pass in the actual parameters / / if you specify the specific data type of the interface's generics when implementing the interface / / this class implements the interface where all methods are generic to replace the actual specific data type class B2 implements IB {@ Override public String test (String s) {return null }} / / generic method class Cc {public void test () {} / / generic method public void test (T s) {T t = s;} public String test1 (String s) {return s; / / generic method public T test1 (T s) {return s;} public void test2 (String...) Strs) {for (String s: strs) {System.out.println (s);}} / / generic method public void test2 (T... Strs) {for (T str: strs) {System.out.println (str);} / / classes with generics can define generic variables class Dd {private E e; / / static generic methods public static void test3 (T t) {/ / generic (this.e) / / in static methods, you cannot use classes to define generics. If you want to use generics, you can only use System.out.println (t) defined by static methods;} / / generics defined on classes can be used in ordinary methods using public void test (T s) {System.out.println (this.e); T t = s;}}

Wildcard character

1. Restricted wildcard characters

(infinitesimal, Person) only allow references to Person and Person subclasses that are generics

[Person, infinity) only allow references whose generics are Person and Person parent classes to call

Only generic calls are allowed for references to implementation classes that implement the Comparable interface

Enumerated class

In some cases, the objects of a class are limited and fixed. For example, the season class can only have 4 objects.

Implement the enumeration class manually:

Private modifier constructor

Properties are decorated with private final

Decorate all instances of this class with public static final

An enumeration class that implements the interface

Like ordinary Java classes, enumerated classes can implement one or more interfaces

If you need each enumeration value to behave differently in the interface method that calls the implementation, you can have each enumeration value implement the method separately.

Public class Test5 {public static void main (String [] args) {/ / Season.SPRING, this execution is to get an object of Season Season spring = Season.SPRING; spring.showInfo (); Season summer = Season.SUMMER; summer.showInfo (); Season spring1 = Season.SPRING / / get the same object every time you execute Season.SPRING, and each enumeration in the enumeration class is a singleton pattern System.out.println (spring.equals (spring1)); spring1.test () }} enum Season implements ITest {SPRING ("spring", "spring blossoms"), / / this is equivalent to calling the private structures with parameters SUMMER ("summer", "hot summer"), AUTUMN ("autumn", "autumn crisp"), WINTER ("winter", "cold wind"); private final String name; private final String desc; Season (String name, String desc) {this.name = name This.desc = desc;} public void showInfo () {System.out.println (this.name + ":" + this.desc);} @ Override public void test () {System.out.println ("this is the test method of the implemented ITest interface");}} interface ITest {void test ();} Annotation (Note) Overview

An Annotation is actually a special tag in the code that can be read at compile, class load, run time, and perform processing accordingly. By using Annotation, programmers can embed some supplementary information in the source file without changing the original logic

Annotation can be used as a modifier for the declaration of packages, classes, constructors, methods, member variables, parameters, and local variables, which are stored in the name=value pair of Annotation

Anotation can be used to set metadata for program elements (classes, methods, member variables, etc.)

Basic Annotation

When using Annotation, add the @ symbol before it and use the Annotation as a modifier. Used to modify the program elements it supports

Three basic Annotation:

@ Override: restricts overriding parent methods. This annotation can only be used for methods.

Deprecated: used to indicate that a program element (class, method, etc.) is out of date

SuppressWarnings: suppresses compiler warnings

Custom Annotation

Customize the new Annotation type using the @ interface keyword

The member variables of Annotation are declared as parameterless methods in the Annotation definition. Its method name and return value define the name and type of the member.

You can specify an initial value for a member variable of Annotation when you define it, and you can use the default keyword to specify the initial value of a member variable.

An Annotation without a member definition is called a tag; an Annotation containing member variables is called an Annotation of metadata.

Import java.lang.annotation.*;import java.util.ArrayList;import java.util.List;public class Test6 {public static void main (String [] args) {new TestB () .test01 (); @ SuppressWarnings ({}) List list = new ArrayList ();}} class TestA {public void test () {}} class TestB extends TestA {@ TestAnn (id = 100, desc = "name") String name @ Override public void test () {super.test ();} @ Deprecated public void test01 () {}} @ Target (ElementType.FIELD) / / this annotation class annotates attributes of other classes @ Retention (RetentionPolicy.RUNTIME) / / defines the declaration period @ Documented@interface TestAnn {public int id () default 0; public String desc () default " } the above is about the content of this article on "how to use the Java set method". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please 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

Internet Technology

Wechat

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

12
Report