《数据结构与算法分析-java语言描述》 - 1.4.3 使用接口类型表示泛型(代码)

       用lang里面的,要重写好多方法。直接在下面重写类算了

应该是这样实现吧。。

package cn.tedu.basic;



public class Demo_FindMax {
	/** * Return max item in arr * Precondition:arr.length>0 * @param arr * @return */
	public static Comparable findMax(Comparable[] arr) {
		int maxIndex = 0 ; 
		for(int i=1 ; i<arr.length ; i++) {
			if(arr[i].compareTo(arr[maxIndex])>0) {
				maxIndex = i ;
			}
		}
		return arr[maxIndex] ; 
	}
	
	/** * Test findMax on Shape and String objects. * @param args */
	public static void main(String[] args) {
		String[] st1 = {
			"123",
			"222",
			"a33",
			"1"
		};
		System.out.println(findMax(st1));
		
		Shape[] sh1 = {
				new Circle(2.0),
				new Shape(3.0),
				new Rectangle(3.0 , 4.0)
		};
		System.out.println(findMax(sh1).getClass());
	}
}

class Shape implements Comparable{ //形状
	double area;
	public Shape(double area){
		this.area = area;
	}
	@Override
	public int compareTo(Object o) {
		Shape anotherShape = (Shape) o;		
		return (int) (this.area - anotherShape.area);
	}
}

class Circle extends Shape{ //圆形
	public Circle(double r) {
		super(r*r*Math.PI);
	}
}


class Rectangle extends Shape{//矩形

	public Rectangle(double l , double w ) {
		super(l*w);
		// TODO Auto-generated constructor stub
	} 
	
}






全部评论

相关推荐

Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
牛客刘北:如果暑期实习是27届的话,你要晚一年才会毕业,企业为什么会等你呢?要搞清时间逻辑呀!27届现在实习只能是在暑假实习,这是日常实习,不是暑期实习。所以多去投日常实习吧,暑期实习肯定不会要你的
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-23 18:30
美团优选内容调整,屁股都没离开座椅呢,多多买菜来挖了
熬夜脱发码农:哈,拼多多真挖人是吧
投递美团等公司8个岗位 >
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务