Java-9.1 type secure Containers
In this section, we will briefly describe the type of secure containers.
When it comes to type security, we have to talk about generics. Of course, here we will just briefly introduce how to use generics, and the subsequent sections will continue.
1. How is data type security?
A counterexample:
package com.ray.ch09;import java.util.ArrayList;public class Test {private ArrayList fruitList = new ArrayList();public void addOrange(Orange orange) {fruitList.add(orange);}public void addApply(Apple apple) {fruitList.add(apple);}public static void main(String[] args) {Test test = new Test();for (int i = 0; i < 5; i++) {test.addApply(new Apple());}for (int i = 0; i < 10; i++) {test.addOrange(new Orange());}}}class Apple {}class Orange {}
From the code above, we can see that Orange is installed in the fruitList and Apply is installed. So when we need get, we only get an Object, which will cause a problem, it is converted to Apply or Orange. If the transformation is incorrect, an exception is thrown during running.
Therefore, if you want to secure the code programming type, you need to use generics. Each List limits the objects to be put.
package com.ray.ch09;import java.util.ArrayList;public class Test {private ArrayList applyList = new ArrayList();private ArrayList
orangeList = new ArrayList
();public void addOrange(Orange orange) {orangeList.add(orange);}public void addApply(Apple apple) {applyList.add(apple);}public static void main(String[] args) {Test test = new Test();for (int i = 0; i < 5; i++) {test.addApply(new Apple());}for (int i = 0; i < 10; i++) {test.addOrange(new Orange());}}}class Apple {}class Orange {}
Each list in the new code can only place specific objects, so there is no type security problem.
The above is the generic type, which limits the type. In this way, there will be no transformation exceptions during operation.
2. for objects that can be transformed up, if they inherit the same class or implement the same interface, they can also be placed in the same generic list.
package com.ray.ch09;import java.util.ArrayList;public class Test {private ArrayList applyList = new ArrayList();public void addApple(Apple apple) {applyList.add(apple);}public static void main(String[] args) {Test test = new Test();for (int i = 0; i < 5; i++) {test.addApple(new Gala());test.addApple(new Fuji());}}}class Apple {}class Gala extends Apple {}class Fuji extends Apple {}
package com.ray.ch09;import java.util.ArrayList;public class Test {private ArrayList
swimList = new ArrayList
();public void add(CanSwim canSwim) {swimList.add(canSwim);}public static void main(String[] args) {Test test = new Test();for (int i = 0; i < 5; i++) {test.add(new Person());test.add(new Fish());}}}interface CanSwim {}class Person implements CanSwim {}class Fish implements CanSwim {}
Summary: This chapter discusses how type security is followed by precautions for type security.