generic paradigm
1. The concept of generics: Generics: Data types that identify elements stored in a collection Writing: <Data Type (Generic)>
// Writing of generics:
// Create a collection and save a b c d
// E Generic Element (Element)
// Note: Types of generics should be consistent (if later filled in)
// jdk1.7 diamond generic
// Later generics can not fill in defaults and the previous consistency
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
// Traversal using iterators
// Iterator generics represent the type of elements saved in the collection [consistent with generics in the implementation class]
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String next = iterator.next();
System.out.println(next);
// If you are an object of your own class, you need to override toString()
}
2. Benefits of generics 1 Ensure data security (prompting you about the type of data to be passed in) 2 Avoid downward transition (type forcing) [prompts you to create what type of object to accept data from iterators] 3 Converts runtime errors into compilation errors [When type accepts errors, no runtime errors are required, prompt directly]
// Create a Collection to Save 3 Students
// Get the 0th student in the collection and print his name
ArrayList<Student> list = new ArrayList<>();
list.add(new Student("Dongdong", 16)); // Benefit 1: Hint you to pass in the student class object in your method
list.add(new Student("generation after generation", 18));
list.add(new Student("Willow willow", 20));
Object object = list.get(0);
Student student = (Student) object; // Benefit 2: It can be accepted directly by students without downward transformation.
// Benefit 3: If the acceptance object is incorrect, it will not need to run to report the error, and the direct error (usually more obvious in the iterator)
3. Generic declarations 1_Declare Location: Class Name (Interface Name) < Generic > Suppose: Student < S > S is a placeholder at this point Note: Usually uppercase letters are used when generics use placeholders (English characters). 2. When do you specify the genuine type of generics? Generic data (object) types are assigned when creating objects
// Examples: generic declarations and specified data types
// The declarative location of generics (the data type of attributes in the Worker class is W)
class Worker<W>{
// Declare member variables with generics
private W w;
// Declare the set/get method
public void setW(W w) {
this.w = w;
}
public W getW() {
return w;
}
// Member method
public void fun(W w) {
System.out.println(w);
System.out.println("I am fun Method");
}
// Can there be more than one generic type in a class? Yes.
// Generic declarations need to be made on Methods
// This generic type will be assigned a parameter (not necessarily an attribute of the class object) when the method is called.
public<Y> void fun1(Y y) {
System.out.println(y);
}
// Can static methods use W generics? No.
// Generics are assigned when methods are called
public static<Q> void fun2(Q q) {
System.out.println(q);
}
}
// Specify the genuine data type for generics
// At this point, the generic placeholder W is assigned String
Worker<String> worker = new Worker<>();
worker.setW("wangjun");
System.out.println(worker.getW());
worker.fun("Youth is stronger than China.");
worker.fun1('1'); // The incoming parameter is a character, and the Y is assigned to char.
// Generics in interfaces
// generic interface
interface InterA<G>{
public abstract void fun(G g);
}
// Generic type determination can be determined on the implementation class of the interface
class InterAImpl implements InterA<String>{
@Override
public void fun(String g) {
// TODO Auto-generated method stub
}
}
Multi-parameter method (int... num)
Int... num (input int type from 0 to num) Acceptable multiple int type values equivalent to an array of parameters [0,1,...num] There are two ways of calling 1. Input values are separated by commas 2. Direct incoming arrays
// The first method (passing in multiple values, separated by commas) calls Note: Different types of parameters can be added, but they should be placed in the front and errors will be reported later. (In other words: int... num is at the end) public static void print(String str,int ... num) { // Traverse (to get how many int s you pass in) for (int i = 0; i < num.length; i++) { System.out.println(num[i]); } } // The second method (input array) separates int[] arr = {2,3,4,5}; print(" ",arr);
Array to set: Arrays. asList (array name), remember to receive with set
// Reasons for errors: You can only place data of reference type in a collection, not basic data type.
int[] array = {1,2,3,4,5};
List<int[]> list = Arrays.asList(array);
System.out.println(list);
// Correctly packed
Integer[] array1 = {1,2,3,4,5};
List<Integer> list1 = Arrays.asList(array1);
System.out.println(list1);
// Create an array of strings to hold three names
// Convert arrays into collections
// Add a name
String[] arr = {"Dongdong","generation after generation","Willow willow"};
// Convert arrays into collections
List<String> list2 = Arrays.asList(arr);
System.out.println(list2);
// Add name
// UnsupportedOperationException
// Operational exceptions are not supported
// Note: This method does not support the length modification of the collection after it has passed through the collection.
// list.add("flower");
// The significance of this approach is that other methods in the collection class can be used
boolean b = list2.contains("generation after generation");
System.out.println(b);
4. Application of generics in inheritance: putting subclasses or subclasses into collections
// Prerequisite: class Student extends Person
// Give an example:
ArrayList<Person> list = new ArrayList<Person>();
list.add(new Student()); // Add subclass
list.add(new Person()); // Add this class
De duplicate
Two general methods 1.for Cycle deletion 2.Iterator deletion
ArrayList<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("b");
list.add("c");
list.add("d"); [a,b,b,c,d] Delete two b
// 1.for loop deletion
for (int i = 0; i < list.size(); i++) {
String string = list.get(i);
if (string.equals("b")) {
list.remove(i--);
// Delete one, move the other forward, if two are continuous, only one can be deleted.
// --, in order to repeat the loop, delete the next b
}
}
System.out.println(list);
// 2. Iterator deletion
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
if (str.equals("b")) {
iterator.remove();
}
}
System.out.println(list);
Collection tool class: Collection.swap(list,i,j) exchange location
Set interface - HashSet implementation class
1. Characteristic of HashSet Implementation Class: Unordered Corner Labels Can't Be Repeated (Inheriting Set Interface) Self-duplicate (premise: object address duplicate, can be de-duplicated, can not be directly de-duplicated according to attributes) 2. Establishment of HashSet Sets
// EstablishSetCollection addition a a b b c c
// Order: The order in which access is stored is the order in which access is taken.
// Iterator traversal
HashSet<String> set = new HashSet<>();
set.add("f");
set.add("a");
set.add("a");
set.add("b");
set.add("b");
set.add("c");
set.add("c");
// Iterator traversal
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
System.out.println(string);
}
//Result:
a,b,c,f(disorder)
3. Automatic de-weighting of Set
HashSet<Man> set = new HashSet<>();
Man m1 = new Man("1",11);
Man m2 = new Man("1",11);
Man m3 = new Man("2",22);
Man m4 = new Man("2",22);
Man m5 = new Man("3",33);
Man m6 = new Man("3",33);
set.add(m1);
set.add(m2);
set.add(m3);
set.add(m4);
set.add(m5);
set.add(m6);
Iterator<Man> iterator = set.iterator();
while (iterator.hasNext()) {
Man m = (Man) iterator.next();
System.out.println(m);
}
//Direct Output: One Undeleted
//There are no reasons why:
// Every object created by the system will be for that object.
// Assign a hashCode value
// When saving objects to HashSet collections
// The system compares hashCode values first.
// Same: Re-invoke the equals method of the object for comparison.
// If the equals method is the same, then it does not exist.
// Conversely, it is stored in the collection
// Different: If HashCode is different, it is equivalent to not being an object.
// Then directly store the object in the collection.
// The equals method will not be called
//Solution:
// Rewriting hashCode and equals methods
// Give an example
/*
* 10 random numbers [10,20] are loaded into a set to be de-duplicated
* Integer It can be weighted directly.
* String It can be weighted directly.
* The system has rewritten hashCode() method and equals() method.
* My own class is not well written, so I have to rewrite it.
*/
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < 10; i++) {
int num = (int)(Math.random() * 11 + 10);
set.add(num);// Automatic boxing
}
System.out.println(set);