Home >Java >javaTutorial >Introduction to Java Collections Framework Architecture

Introduction to Java Collections Framework Architecture

零下一度
零下一度Original
2017-07-23 10:24:532638browse

1. Overview of sets<br>

1) The concept of sets

Sets in real life: many things put together .

Set in mathematics: a collection of things with common properties.

The collection class in Java: is a tool class, like a container, that stores any number of objects with common properties.

2) The role of collection

If there are multiple properties of the same type inside a class, and their functions and meanings are the same. For example, a student can choose multiple courses. For a student class, XX course is one of his attributes, and there is usually more than one XX course. For situations like this, it would be too cumbersome to define an attribute for each course. Here we have to use the concept of sets.

To sum up, the functions of sets have the following points:

  1. ##In Within the class, the data is organized.

  2. Search large quantities of items simply and quickly.

  3. Some collection interfaces provide a series of ordered elements, and related elements can be quickly inserted or deleted in the middle of the sequence.

  4. Some collection interfaces provide mapping relationships, and you can quickly find the corresponding unique object through the key (key), and this key can be of any type.

3) Comparison between sets and arrays

It can be seen that sets and arrays have similar functions. They both put a series of data into a container, but Why do we use sets instead of arrays inside classes?

  1. The length of the array is fixed, and the length of the collection is variable. The advantage of a collection is that the length of the collection expands with the content inside, while the length of the array is already defined.

  2. Arrays can only access elements through subscripts, and the type is fixed (array subscripts can only be integers), while some

    collections can find the mapped specific elements through any type. Object (key keyword can be of any type).


2. Java Collection Framework Architecture

Let’s take a brief look at the java collection framework: (There are many interfaces and classes not listed , only commonly used interfaces and classes are listed here)

As shown in the figure, JAVA collection framework architecture: Collection and Map are the two root interfaces.

Collection interface: The internal storage is an independent object. Contains:

1, List interface:

sequence, storage elements are arranged in order and repeatable. Implementation class: ArrayList, array sequence; Implementation class: LinkedList, linked list.

2. Queue interface:

Queue, the storage elements are arranged in an orderly and repeatable manner. Implementation class: LinkedList, linked list.

3. Set interface:

set, which stores elements unordered and non-repeatable. Implementation class: HashSet, hash set.

Map interface: Internally uses a mapping of (any type) to store data. This mapping is the Entry class (internal of Map class) instance. Includes: Implementation class: HashMap, hash table.

The Collection interface is the parent interface of the List, Set, and Queue interfaces. The Collection interface defines methods that can be used to operate List, Set, and Queue - add, delete, modify, and query. (The specific Collection interface methods can be found by checking the API, so they will not be listed here.)

Among them, ArrayList, HashSet and HashMap are the three most commonly used implementation classes. Here we will introduce these three implementations one by one. kind.

In this article, we will first introduce the usage of ArrayList.


3. ArrayList implementation class

<br>

List interface and its implementation class--ArrayList

List can accurately control the insertion position of each element, or delete an element at a certain position;

List has an add() insertion method and a get() acquisition method;

ArrayList--Array sequence is an important implementation class of ListThe bottom layer of

ArrayList is implemented by array, which is also the origin of its name.

So how to use these collections? Let's use a small example and write a small program to learn how to use sets more intuitively. (The examples in subsequent articles are also based on this) ;>>>>>>>>>>>>>>>>>>>>>>>>> ;>>>

Program function - simulate student course selection function

Select courses (add courses to the collection)

  1. Delete a selected course (delete elements in the collection)

  2. View the selected course

  3. Modify selected courses

  4. ##>>>>>>>>>>>>>> ;>>>>>>>>>>>>>>>>>>>>>>>>> ;>>>

The following is a code snippet of the program. It is used for testing to introduce the use of collections, so please don't worry about the details. The code will be improved step by step. . 1) Create student class and course class

 1 /** 2  * 学生类 3  * @author hysum 4  * 5  */ 6 public class Student implements { 7     private String name;//学生姓名 8     private String id;//学生id 9     private Set courses;//所选课程的set集合10     11     public Student(){}12     public Student(String id,String name){13         this.id=id;14         this.name=name;15         this.courses=new HashSet();//初始化集合16     }17     public String getName() {18         return name;19     }20     public void setName(String name) {21         this.name = name;22     }23     public String getId() {24         return id;25     }26     public void setId(String id) {27         this.id = id;28     }29     public Set getCourses() {30         return courses;31     }32     public void setCourses(Set courses) {33         this.courses = courses;34     }

 1 /** 2  * 课程类 3  * @author hysum 4  * 5  */ 6 public class Course { 7 private String id;//课程id 8     private String name;//课程名称 9     10     public Course(){11         12     }13     public Course(String name){14         this.name=name;15     }16     public String getId() {17         return id;18     }19     public void setId(String id) {20         this.id = id;21     }22     public String getName() {23         return name;24     }25     public void setName(String name) {26         this.name = name;27     }28     public Course(String id,String name){29         this.id=id;30         this.name=name;31     }32 }

2) Create alternative course class
 1 /** 2  * 备选课程类 3  * 
 4  * @author hysum 5  * 6  */ 7 public class ListCourse { 8 private List CoresesToSelect;// 备选课程 9     private Student stu;10     private static Scanner in;11     {12         in = new Scanner(System.in);13     }14     public ListCourse() {15         this.CoresesToSelect = new ArrayList();// 初始化List集合16     }17        public List getCoresesToSelect() {18         return CoresesToSelect;19     }20 21     public void setCoresesToSelect(List coresesToSelect) {22         CoresesToSelect = coresesToSelect;23     }   26 }

Note:

List is an interface, so it cannot be instantiated directly in the constructor, but is instantiated through ArrayList()! ! !

Example: public List coursesToSelect = new ArrayList();

Set and Map are similar. They cannot be instantiated directly. You must use the corresponding instantiation class. Such as HashSet(), HashMap();

3) Add courses to alternative courses

(Add elements) There are a total of 4 methods to insert elements into List under List:

1.add(element);

2.add(index,element);

3.addAll(Arrays.asList(object array name));

4.addAll(index,Arrays.asList(object array name));

The following code example:

 1 /* 2  * 添加备选课程 3  */ 4 public void AddCourse() { 5         Course cr1=new Course("1","数据结构");//创建课程对象 6     this.CoresesToSelect.add(cr1);//用add(element)添加  7         Course temp=(Course)this.CoresesToSelect.get(0);//用get方法取出,注意类型转换 8     System.out.println("添加了课程:"+temp.getId()+" "+temp.getName()); 9         10         Course cr2=new Course("2","C语言");//创建课程对象11     this.CoresesToSelect.add(0,cr2);//用add(index,element)添加 12     temp=(Course)this.CoresesToSelect.get(0);13         System.out.println("添加了课程:"+temp.getId()+" "+temp.getName());  
14 }

1 Course[] course = { new Course("1", "数据结构"), new Course("2", "C语言"), new Course("3", "汇编语言"),2                 new Course("4", "离散数学") };3         this.CoresesToSelect.addAll(Arrays.asList(course));//用addAll(Arrays.asList(对象数组名))添加

Note:
1. When objects are stored in a collection, they become object types and require type cast when they are taken out. (

We will use generics to solve this problem later)

Example: Course temp = (Course)coursesToSelect.get(0);

2. The position (index) added to the list is between [0, length]; 0 means inserting at the head of the queue, and length means inserting at the end of the queue.

3. If the length added to the List is greater than its current length, an exception will occur in the system, that is, an out-of-bounds exception in the table below the array, such as:

1 Course cr2=new Course("2","C语言");//创建课程对象2 this.CoresesToSelect.add(2,cr2);//用add方法添加,超出集合现有长度 temp=(Course)

4) Alternative course removal and printing

The following three methods are used to remove elements from the List:

-----for loop- ----

1 public void testGet(){2 int size=CoursesToSelect.size();3 for(int i=0;i<size;i++){4 Course cr=(Course) CoursesToSelect.get(i);5 System.out.println("取出的课程:"+cr.getId()+":"+cr.getName());6 }7 }

-----Iterator-----

Iterator is an interface that relies on the existence of a collection.

1 Iterator it=CourseToSelect.iterator();2 while(it.hasNext()){3 Course cr=(Course) it.next();4 System.out.println("课程:" + cr.id + ":" + cr.name);5 }

-----for each(recommended to use

)-----
1 for(Object obj:CoursesToSelect){//遍历集合中的每一个元素,作为每一个Object变量2 Course cr=(Course) obj;3 System.out.println("课程:" + cr.id + ":" + cr.name);4 }

5) Alternative course modification

Use set (index, Object element) to modify the element, index represents the index position, and element represents the new object.
1     /*2      * 修改备选课程3      */4     public void Modify(int index, Course c) {// 传入要修改的参数5         this.CoresesToSelect.set(index, c);6     }

6) Delete alternative course elements

List has remove(index), remove(object value) and removeAll(Arrays.asList(object array name) ) method to delete the value of an element in the container (usage is similar to add).
Course is an information course class with id and name attributes; courseToSelect is a sequence container object of list.

 1     /* 2      * 删除备选课程,跟添加方法类似 3      */ 4     public void Remove(int index) {// 通过索引位置删除 5         this.CoresesToSelect.remove(index); 6     } 7  8     public void Remove(Course c) {// 通过课程对象删除 9         this.CoresesToSelect.remove(c);10 11     }12 13     public void Remove(Course[] c) {// 通过集合对象删除14         this.CoresesToSelect.removeAll(Arrays.asList(c));15 16     }

注意:

1.remove(index);删除位置要大于0并且小于List(序列容器)的长度。如果要删除全部可以用for循环嵌套此方法。

2.remove(object);先要获得删除的值,用法是先定义一个信息变量通过get()来存放要删除的值,然后用remove(删除的对象值);

3.removeAll(Arrays.asList());要删除指定的多个位置 Arrays.asLIst(对象数组名);作用是把数组转换为集合。用法是先创建信息对象数组存放删除元素的值,然后再用removeAll(Arrays.asList(对象数组名))方法,删除集合数组的元素。


四、应用泛型管理课程

在上面的几个例子中,小伙伴是否发现对于集合的取出和遍历都要将Object对象进行强制转换后才能使用,每次这样做不仅增加了编程难度还使代码特别繁琐,这里我们可以利用泛型来帮助我们更加方便地使用java集合。

首先,我们要知道没有使用泛型的话集合中的元素,可以是任意类型的对象(对象的引用),如果把某个对象放入集合,则会忽略他的类型把他当做Object处理。

那么我们就在刚才的例子里往备选课程类里的CoresesToSelect的List集合添加一些奇怪的东西会发什么有趣的事呢?

1    /*2      * 往List中添加一些奇怪的东西3      */4      public void testType(){5      System.out.println("能否往List中添加一些奇怪的东西呢?");6      this.CoresesToSelect.add("我不是课程,我是字符串!");7      }

当调用取出课程方法取出该元素时,运行时出错:

这是因为取出该元素时String类型不能强制转换为Course类型,那有什么办法来避免集合中被添加不希望添加的类型呢?

泛型则是规定了某个集合只可以存放特定类型的对象,会在编译期间进行类型检查,可以直接指定类型获取的集合元素。

泛型:指规定了某个集合只能存放特定类型的对象。

语法:ArrayList<String> array=new ArrayList<String>();  //规定array中只能存放String类型的对象

那么,了解了泛型之后,上面的例子里都可以加上泛型了,修改如下(只列出修改的部分):(自行对比)

1 private Set<Course> courses;//所选课程的set集合2 this.courses=new HashSet<Course>();//初始化集合3 public Set<Course> getCourses() {4         return courses;5     }6     public void setCourses(Set<Course> courses) {7         this.courses = courses;8     }
 1 private List<Course> CoresesToSelect;// 备选课程 2 public ListCourse() { 3         this.CoresesToSelect = new ArrayList<Course>();// 初始化List集合 4     } 5 public List<Course> getCoresesToSelect() { 6         return CoresesToSelect; 7     } 8  9     public void setCoresesToSelect(List<Course> coresesToSelect) {10         CoresesToSelect = coresesToSelect;11     }

foreach循环的修改:

1 for (Course obj : CoresesToSelect) {        
2     System.out.println("添加了课程:" + obj.getId() + " " + obj.getName());4 }
<br>

运用了泛型的话,用foreach语句时 存储变量应该为泛型的类型。for(Course a:courseToSelect),不必再用Object取出再强转,因为已经规定容器里装的都是Course类型。

使用泛型要注意

1.泛型集合中,不能添加泛型规定的类型和其子类以外的对象,否则会报错!

2.泛型中可以添加规定的类型的子类型的对象。如:

1 public void testChild() {2         ChildCourse ccr = new ChildCourse();3         ccr.id = "3";4         ccr.name = "我是子类型的课程对象实例~~";5         courses.add(ccr);6 }

3.不能直接添加基本类型(int,float等)的对象,如果要添加,需要使用其包装类。如:

1 public void testBasicType() {2 List<Integer> list = new ArrayList<Integer>();3 list.add(1);4 System.out.println("基本类型必须使用包装类作为泛型!" + list.get(0));5 }

五、通过Set集合管理课程

Set集合和List一样是Collection接口的子接口。它的方法跟List类似,但有稍许不同,因为Set集合是无序且不重复的。

1)添加学生选课的课程

add方法跟ArrayList一样

 1 li.stu=new Student("1","小明"); 2         System.out.println("欢迎"+li.stu.getName()+"同学选择课程"); 3         for(int i=0;i<3;i++){//循环三次添加选课 4             System.out.println("请选第"+(i+1)+"门课程:"); 5             String Id=in.next(); 6             for(Course c:li.getCoresesToSelect()){ 7                 if(c.getId().equals(Id)){ 8                     li.stu.getCourses().add(c); 9                 }10             }11             12         }

注意:Set 中添加某个对象,无论添加多少次,最终只会保留一个该对象(的引用)。同时,保留的是第一次添加的那一个。Set集合是无序的不可重复的。

2)打印输出学生选的课程

1 //输出学生选的课程2         for(Course c:li.stu.getCourses()){3             System.out.println(c.getId()+" "+c.getName());4 5         }

Note: You can only use foreach or iterator to loop through each element in the Set, and you cannot use the get() method like List. Because it is unordered, the output results will be slightly different each time.

##>>>>>>>>>>>>>>>>>>

Summary:

1. Set is not modified like the set() method in List, because List is ordered and the position can be specified. , and Set is unordered and can be modified by loop traversal.

2. When querying and traversing, the Set cannot be obtained using the get() method, because the index ID is not specified in the unordered order, but you can use foreach and iterator to traverse, but the order may be different each time it is traversed. It's still caused by disorder.

3. size(), add(), addAll(), remove(), removeAll() in Set are similar to List.

4. Set can also add null (but only one null can be added because it is not repeated);

The above is the detailed content of Introduction to Java Collections Framework Architecture. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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