demo01
Demo01:
package edu.xcdq.demo01;
import java.util.ArrayList;
import java.util.List;
public class Demo01 {
public static void main(String[] args) {
// 为了解决通用性的问题,jdk提供了封装好的集合,但是集合可以存放不同类型的数据
List list = new ArrayList();
list.add("111");
list.add(111);
list.add(true);
list.add(11.1);
System.out.println(list);
// 加入泛型,做约束
ArrayList<String> alist = new ArrayList<>();
alist.add("111");
// alist.add(111);加入了泛型,不可以存储泛型之外的数据类型
}
}
demo02
Demo02:
public class Demo02 {
public static void main(String[] args) {
Pair<Integer> pair1 = new Pair<>(1,2);
System.out.println(pair1);
Pair<Double> pair2 = new Pair<>(1.1,1.2);
System.out.println(pair2);
Pair<String> pair3 = new Pair<>("haha","hehe");
System.out.println(pair3);
}
}
Pair:
public class Pair <T>{ //type
private T first;
private T second;
//构造方法
public Pair(){
}
public Pair(T first,T second){
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getSecond() {
return second;
}
public void setSecond(T second) {
this.second = second;
}
}
demo03
ArrayAlg:
public class ArrayAlg {
// 求出所有通用的数据中间位置的值
public static <T> T getMiddle(T[] a){
return a [a.length /2];
}
}
Demo03:
public class Demo03 {
public static void main(String[] args) {
Integer [] a = {1,2,3 ,4,5 };
System.out.println(ArrayAlg.getMiddle(a));
String[] str = {"111","222","333"};
System.out.println(ArrayAlg.getMiddle(str));
}
}
demo04
Canvas:
public class Canvas {
public void draw(Shape shape){
shape.xingzhuang();
}
//在画布上花多个
public void drawAll (List<Shape> shapeList){
for ( Shape s : shapeList){
s.xingzhuang();
}
}
}
Shape:
public abstract class Shape {
public abstract void xingzhuang();
}
Circle:
public class Circle extends Shape {
public void xingzhuang(){
System.out.println("正在画圆");
}
}
Rectangle:
public class Rectangle extends Shape {
public void xingzhuang(){
System.out.println("正在矩形");
}
}
Demo04:
public class Demo04 {
public static void main(String[] args) {
Canvas canvas = new Canvas();
Circle circle = new Circle();
canvas.draw(circle);
//定义多个形状,组成一个数组列表,传入
Circle circle1 = new Circle();
Rectangle rectangle = new Rectangle();
Rectangle rectangle1 = new Rectangle();
Circle circle2 = new Circle();
ArrayList<Shape> list = new ArrayList<>();
list.add(circle1);
list.add(rectangle);
list.add(rectangle1);
list.add(circle2);
canvas.drawAll(list);
}
}