java基础:19.2 泛型举例,矩阵的运算
发布日期:2022-04-04 06:36:31
浏览次数:23
分类:博客文章
本文共 1828 字,大约阅读时间需要 6 分钟。
首先创建一个泛型类,<E extends Number>
表示该泛型类型是Number的子类型。
抽象
方法,因为不知道元素的确切类型前不能实现它。后面写的所有方法都是非静态的,因为我们使用的是泛型类型E来表示类。 public abstract class GenericMatrix{ //矩阵元素的类型是Number 的泛型子类 protected abstract E add(E o1, E o2); protected abstract E multiply(E o1, E o2); protected abstract E zero(); //零矩阵 //矩阵的加法运算、乘法运算、结果显示 public E[][] addMatrix(E[][] matrix1, E[][] matrix2) { //将两个矩阵相加,用泛型E来表示类,所以方法是非静态的; if ( (matrix1.length != matrix2.length) || (matrix1[0].length != matrix2[0].length) ) throw new RuntimeException("The matrices do not have the same size!"); E[][] result = (E[][]) new Number[matrix1.length][matrix1[0].length]; //注意E[][] result = new Number[matrix.length][matrix1[0].length]是不对的, //因为不能用泛型类型来创建数组,要用(E[][])来转换才能创建数组; for(int i = 0 ;i < result.length; i++) for (int j = 0; j
接下来是对GenericMatrix的Integer示例的部分函数重载该程序实现了Integer 对象的add 、multiply 和zero 方法。因为这些方法只能被addMatrix 和multiplyMatrix 方法调用,所以,它们仍然是protected 的。
public class IntegerMatrix extends GenericMatrix{ @Override protected Integer add(Integer o1,Integer o2) { return o1 + o2; } @Override protected Integer multiply(Integer o1,Integer o2) { return o1 * o2; } @Override protected Integer zero() { return 0; }}
main函数
public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Integer[][] m1 = new Integer[][] {{1,2,3},{4,5,6},{1,1,1}}; Integer[][] m2 = new Integer[][] {{1,1,1},{2,2,2},{0,0,0}}; IntegerMatrix integerMatrix = new IntegerMatrix(); System.out.println("\n m1 + m2 is "); GenericMatrix.printResult(m1, m2, integerMatrix.addMatrix(m1, m2), '+'); System.out.println("\n m1 * m2 is "); GenericMatrix.printResult(m1, m2, integerMatrix.multiplyMatrix(m1, m2), '*'); }}
显示结果
转载地址:https://www.cnblogs.com/l20902/p/10610895.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月20日 11时46分08秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
使用MATLAB加载文本数据
2019-04-27
使用MATLAB加载csv格式数据
2019-04-27
C语言换行带来的问题
2019-04-27
使用Python实现拉马努金的三角函数正弦公式
2019-04-27
使用Python求解最小公倍数
2019-04-27
Windows上实现dos命令重命名
2019-04-27
使用Python通过win32 COM接口实现Excel单元格写入
2019-04-27
使用命令行工具编译C#程序
2019-04-27
C#中的局部变量冲突
2019-04-27
C语言读取二进制文件
2019-04-27
解决GVIM中C-A组合键不起作用的问题
2019-04-27
VS中定义的DEBUG常量
2019-04-27
C#中warning预处理命令的使用
2019-04-27
C#中error预处理命令的使用
2019-04-27
MATLAB中限值模块的使用
2019-04-27
树莓派显示黑边问题解决
2019-04-27
树莓派的硬件信息了解与思考
2019-04-27
树莓派安装截图工具
2019-04-27
树莓派上创建个人用户
2019-04-27
树莓派CPU超频配置
2019-04-27