title: Array and Generics
date: 2023-12-30
author:
- AllenYGY
status: DONE
tags:
- NOTE
- Java
- Lec7
- Program
created: 2023-12-30T00:59
updated: 2024-05-31T00:54
publish: True
Array and Generics
array 一经创建长度不可变
Declare an array a of integers:
int[] a; int b[];
Create an array object that can hold 100 integers:
a = new int[100];
Array literal:
int [] array = {1,2,3,4,5}
Length
a.length;
创建后需要使用 new 方法 初始化对象
Student[] a; // Variable.
a = new Student[3]; // Array object.
System.out.println("length: " + a.length);
// Creating all the array elements one by one:
for(int i = 0; i < a.length; i++) {
a[i] = new Student("Student " + i); //* neeed to new an object
}
for(int i = 0; i < a.length; i++) {
// a[i] is of type Student.
System.out.println("name: " + a[i].getName());
}
for (elementType varName : arrayName){
…statement…
}
for(Student s: a) {
System.out.println("name: " + s.getName());
}
for(int i = 0; i < a.length; i++) {
Student s = a[i];
System.out.println("name: " + s.getName());
}
Because varName is only a synonym for arrayName[i], and is not arrayName[i] itself, modifying varName does not modify the array object!
It is not possible to use an enhanced for loop to modify the array object.
It is possible to use an enhanced for loop to modify the element objects!
element object 可以修改, array 本身不可变
The array elements are always all accessed one by one in order of increasing index (from 0 to length - 1) and there is no way to change that.
Do not confuse the array object with its element objects!
ArrayList a; // Variable.
a = new ArrayList(); // ArrayList object.
// Loop up to 3 because a.size() is 0 initially.
for(int i = 0; i < 3; i++) {
a.add(new Student("Student " + i)); // Upcast.
}
for(int i = 0; i < a.size(); i++) {
Student s = (Student)a.get(i); // Downcast.
System.out.println("name: " + s.getName());
}
public class Generics<T>{
Random random=new Random();
private T product;
public ArrayList<T> products=new ArrayList<>();
public Generics(){
}
public void addproduct(T product){
products.add(product);
}
public T getproduct(){
product=products.get(random.nextInt(products.size()));
return product;
}
public static void main(String[] args) {
Generics<String> sGenerics=new Generics<>();
String [] sProducts={"Iphone","Iwatch","Mac","airpods"};
for (int i = 0; i < sProducts.length; i++) {
sGenerics.addproduct(sProducts[i]);
}
System.out.println("You get "+sGenerics.getproduct());
}
}