JAVA范例 十) 内部类与接口

      内部类与接口

  10.1 成员内部类

  实例175 成员内部类的使用规范

package Chapter10;
public class MembersInternal {
	public static void main(String[] args) {
		OuterClass out = new OuterClass(30, 60); 		// 实例化对象
		OuterClass.InnerClass in = out.new InnerClass();	// 实例化成员内部类
		System.out.println("OuterClass是一个" + out.var);
		System.out.println("InnerClass是一个" + in.var);
		in.showVarValue(); 							// 调用showVarValue()方法
		in.innerMethod(); 							// 调用innerMethod()方法
	}
}
class OuterClass {
	String var = "外部类";
	private int width = 10;
	private static int height = 100;
	public OuterClass(int width, int height) { 				// 带参数的构造方法
		this.width = width;
		this.height = height;
		System.out.println("参数:width = " + this.width + ",height = "
				+ this.height);
	}
	private void outerOne() { 							// 外部类非静态方法
		System.out.println("系统正在访问外部类的非静态方法");
		InnerClass inner = this.new InnerClass();			// 外部类创建内部类对象
	}
	private static void outerTwo() { 						// 外部类的静态方法
		System.out.println("系统正在访问外部类的静态方法");
	}
	class InnerClass { 								// 定义成员内部类
		String var = "内部类";
		public InnerClass() { 						// 默认构造方法
			System.out.println("创建了一个内部类对象");
		}
		protected void showVarValue() {				// 内部类调用外部类的private变量
			System.out.println("外部类的width变量值为:" + width);
			System.out.println("外部类的height变量值为:" + height);
		}
		protected void innerMethod() {					// 成员内部类的非静态方法
			System.out.println("允许内部类访问外部类的private方法");
			outerOne();
			outerTwo();
		}
	}
}

 

  实例176 猜谜

package Chapter10;
public class Riddles {				// 测试类
	public static void main(String[] args) {
		System.out.println("猜迷游戏开始了~~~~\n");
		Animals am = new Animals("两撇小胡子 油嘴小牙齿 ", " 喜欢偷油吃 ");// 创建Animals类对象
		am.setEvaluation("贼头又贼脑");	// 为Animals类的evaluation变量赋值
		// 调用Animals的属性变量
		System.out.println(am.features);
		System.out.print(am.evaluation);
		System.out.println(am.hobbies);
		am.setResult("老鼠");			// 设置迷底
		am.question();					// 调用question方法
		am.showResult();				// 调用showResult方法
		System.out.println();
		Animals.Plant plant = am.new Plant("高高绿骨儿 圆圆金黄脸 ", "最爱向太阳 ");// 创建Plant类对象
		am.setEvaluation("盈盈笑不停");	// 通过Animals类的setEvaluation方法为evaluation变量赋值
		plant.setAnswer("向日葵");		// //设置迷底
		// 调用Animals的属性变量
		System.out.println(am.features);
		System.out.print(am.hobbies);
		System.out.println(am.evaluation);
		plant.question();				// 调用question方法
		plant.showAnswer();				// 调用showResult方法
	}
}
class Animals {
	String features;						// 特征
	String hobbies;						// 习惯
	String evaluation;					// 评价
	private String result;					// 答案
	Animals(String features, String hobbies) {	// 用构造方法为变量features和hobbies赋值
		this.features = features;
		this.hobbies = hobbies;
	}
	public void showResult() {				// 显示迷底
		System.out.println("迷底:[" + result + "]");
	}
	public void setResult(String result) {		// 给result变量赋值
		this.result = result;
	}
	public void setEvaluation(String evaluation) {	// 给evaluation变量赋值
		this.evaluation = evaluation;
	}
	public void question() {					// 提出问题
		System.out.println("请你猜一猜,它会是一种什么动物呢?");
	}
	class Plant {
		Plant(String f, String b) {				// 用该类的构造方法为变量features和hobbies赋值
			features = f;
			hobbies = b;
		}
		public void question() {				// 提出问题
			System.out.println("请你猜一猜,它会是一种什么植物呢?");
		}
		public void setAnswer(String answer) {	// 设置迷底答案
			setResult(answer);				// 调用Animals类的setResult方法
		}
		public void showAnswer() {			// 显示迷底
			showResult();					// 调用Animals类的showResult方法
		}
	}
}

 

  10.2 方法内部类

  实例177 局部内部类的使用规范 

package Chapter10;
public class LocalInternal {
	public static void main(String[] args) {
		OuterClass_1 out = new OuterClass_1(); 	// 实例化对象
		Local local = out.result(); 				// 调用方法返回抽象类
		local.A_local(); 					// 调用抽象类的抽象方法
		local.B_local();
		local.C_local();
	}
}
abstract class Local { 						// 定义一个抽象类
	public abstract void A_local(); 				// 定义三个抽象方法
	public abstract void B_local();
	public abstract void C_local();
}
class OuterClass_1 { 						// 外部类
	private String str = "现在访问的是外部类";
	private void p_showMess() {
		System.out.println("现在访问的是外部类的私有非静态变量——p_showMess()");
	}
	public void showMess() {
		System.out.println("现在访问的是外部类的非静态方法——showMess()");
	}
	public Local result() { 					// 方法返回实现的抽象类的局部内部类
		final String inner = "局部内部类是在方法中创建的类";
		class InnerClass_1 extends Local { 		// 定义局部内部类并继承抽象类,实现抽象方法
			public void A_local() {
				showMess();
			}
			public void B_local() {
				p_showMess();
			}
			public void C_local() {
				System.out.println("显示局部内部类的成员常量inner: \"" + inner + "\"");
				System.out.println("调用外部类的成员变量str: \"" + str + "\"");
			}
		}
		return new InnerClass_1();
	}
}

 

  实例178 奖学金的评分标准

package Chapter10;
public class ScoreTest {
	public static void main(String[] args) {
		System.out.println("奖学金的评分标准:\n 总成绩 = 学习总成绩+学生干部奖励分+表现分");
		OuterClass_3 out = new OuterClass_3("尹继平",true,5,91.75);//创建外部类对象
		//调用外部类的变量
		System.out.println("姓名:"+out.name);
		System.out.print("此人是班级干部吗?");
		System.out.println(out.isCadre?"是":"不是");
		System.out.print("此人参加过几次学生会组织的活动?");
		System.out.println(out.times>0?out.times+"次":"没参加过");
		if(out.isCadre){		//判断此人是否是班干部,true表示是,false表示不是
			out.add(3);	//如果是则加3分
		}else{
			out.add(0);
		}
	}
}
class OuterClass_3 {
	String name;				//姓名
	boolean isCadre = false;		//是否是班干部
	int times = 0;				//参加活动的次数
	int sum = 0;				//参加活动得的分数
	double score ;				//学习总成绩
	OuterClass_3(String name, boolean isCadre, int times, double score) {//利用构造方法为其成员变量赋值
		this.name = name;
		this.isCadre = isCadre;
		this.times = times;
		this.score = score;
	}
	{
		if (times > 0) {			//判断是否参加过活动
			sum = 1 * times;//每参加一次活动,就获得1分
		}
	}
	void add(final int s) {						//算取成绩
		final int temp = sum;
		class InnerClass_3 {					//定义局部内部类
			void display() {					//显示最后的成绩
				System.out.println("该生的最后成绩: score = " + (score + s + temp));
			}
		}
		InnerClass_3 in = new InnerClass_3();	//创建内部类对象
		in.display();//调用其内类方法
	}
}

 

  10.3 匿名内部类

  实例179 匿名内部类的使用规范

package Chapter10;
public class AnonymousInternal {
	public static void main(String[] args) { 		// java程序主入口处
		// 所有方法的调用
		createIinterface().showMess();
		createAbstract().showMess();
		createClass().showMess();
	}
	public static A_interface createIinterface() {
		A_interface inter = new A_interface() { 	// 创建接口的匿名内部类
			public void showMess() { 			// 实现接口中的方法
				System.out
						.println("1. 在匿名内部类中,实现了A_interface接口中定义的showMess方法.");
			}
		};
		return inter;
	}
	public static A_abstract createAbstract() {
		A_abstract ab = new A_abstract() { 		// 创建抽象类的匿名内部类
			void showMess() { 				// 实现抽象类中定义的抽象方法
				System.out
						.println("2. 在匿名内部类中,实现了A_abstract类中的抽象方法:showMess().");
			}
		};
		return ab;
	}
	public static A_class createClass() {
		A_class ac = new A_class() {				// 创建普通类的匿名内部类
			public void showMess() { 				// 实现方法的重写
				System.out.println("3. 在匿名内部类中,重写了A_class类中的showMess方法.");
			}
		};
		return ac;
	}
}
interface A_interface { 							// 定义一个接口
	public void showMess();
}
abstract class A_abstract { 						// 定义一个抽象类
	abstract void showMess();
}
class A_class { 								// 定义一个类
	public void showMess() {
		System.out.println("这是一个普通的类");
	}
}

 

  实例180 电话与移动电话

package Chapter10;
public class Parameter {
	public static void main(String[] args) {
		Mobile mb = new Mobile();	// 创建Mobile对象
		mb.function();				// 调用Mobile的function方法
	}
}
interface Phone {					// 电话接口
	public void Call();				// 拔电话号码
	public void Answer();				// 接电话
}
class Mobile {						// 移动电话类
	String name;					// 联系人的姓名
	String phoneNum;				// 联系人的电话号码
	Phone p;						// 声明Phone变量
	void function() {					// 移动电话的功能
		class Person {				// 创建人类
			Person(String name1, String num) {			// 利用构造方法为Mobile类的成员变量赋值
				name = name1;
				phoneNum = num;
			}
			void contact(Phone p) {					// 创建一个抽象方法
			};
		}
		Person per = new Person("聂庆亮", "13220073610");// 创建Person对象
		per.contact(p = new Phone() {// 调用contact方法,其中以匿名内部类为参数,并为Phone类变量赋值
			// 重写Phone接品的所有抽象方法
			public void Answer() {
				System.out.println("我正在和" + name + "通电话呢。");
			}
			public void Call() {
				System.out.println("我正在给电话号码为" + phoneNum + "打电话呢。");
			}
		});
		// 调用Phone类中的方法
		p.Answer();
		p.Call();
	}
}

 

  10.4 静态内部类

  实例181 静态内部类的使用规范

package Chapter10;
public class StaticInternal {
	private static String name = "\"聂庆亮\"";
	public static void setStatic(String n) {		// 外部类的非静态方法
		System.out.println("[现在访问的是外部类的静态方法!]");
		name = n;
	}
	static class InnerClass_2 {			// 静态内部类开始
		String address, mail;		// 声明String类型变量
		long phoneNum;		// 声明long类型变量
		int qq;				// 声明int类型变量
		static void getStatic() {	// 静态内部类的静态方法
			System.out.println("[访问外部类的静态变量] name = " + name);
			setStatic("尹继平"); 	// 访问外部类的静态方法
		}
		// 静态内部类的非静态方法
		public void setString(String address, String mail) {
			System.out.println("1.静态内部类的带String型参数的非静态主法");
			this.address = address;
			this.mail = mail;
		}
		public void setInt(long phoneNum, int qq) {
			System.out.println("2.静态内部类的带int型参数的非静态主法!");
			this.phoneNum = phoneNum;
			this.qq = qq;
		}
	}							// 静态内部类结束
	public void setValue() { 			// 外部类访问静态内部类的静态成员:内部类.静态成员
		InnerClass_2.getStatic(); 		// 访问静态内部类的静态方法
		InnerClass_2 inner = new InnerClass_2(); 				// 实例化对象
		inner.setString("北京昌平区沙河镇", "yinjiping@sina.com"); 	// 访问静态内部类的非静态方法
		inner.setInt(89653310, 313557706);
		System.out.println("\n外部类访问静态内部类的结果如下:");
		System.out.println("姓名:" + this.name);
		System.out.println("住址:" + inner.address);
		System.out.println("联系电话" + inner.phoneNum);
		System.out.println("E-mail:" + inner.mail);
		System.out.println("QQ号码:" + inner.qq);
	}
	public static void main(String[] args) {						// java程序主入口处
		StaticInternal sin = new StaticInternal();
		sin.setValue(); 										// 调用方法
	}
}

 

  实例182 苹果的来历

package Chapter10;
public class Plant {
	public String shape ="椭圆型";				//叶子的形状
	private static String color = "白色";			//花的颜色
	private String grow="黑土地";				//生长的环境
	public static void main(String[] args) {
		Fruit f = new Fruit();					//创建Fruit类
		f.print();							//调用Fruit类的print方法
		new Apple().main(args);				//调用Apple类main方法
	}
	static class Fruit{
		String taste ;						//味道
		boolean iron;						//是否有果核
		Fruit(){							//给变量赋初值
			this.taste = "酸";
			this.iron =true;
		}
		public void print(){
			//调用外部类的变量
			System.out.println("叶子的形状:"+new Plant().shape);
			System.out.println("花的颜色:"+color);
			System.out.println("生长的环境:"+new Plant().grow);
		}
	}
}
class Apple extends Plant.Fruit {
	Apple(String taste) {		// 自定义带参构造方法
		this.taste = taste;	// 重新给taste变量赋值
	}
	Apple() {
		super();			// 调用父类的构造方法
	}
	public static void main(String[] args) {
		Apple apple = new Apple(); // 创建Apple对象
		// 调用父类的变量
		System.out.println("水果的味道:" + apple.taste);
		System.out.println("是否有核:" + apple.iron);
	}
}

 

  10.5 接口

  实例183 求n的幂数与倍数

package Chapter10.inter;
public class Example {
	public static void main(String[] args) {
		PowerOfFive five = new PowerOfFive();
		MultOfFive fiOb = new MultOfFive();
		Number ob;
		System.out.println("求5的n次方的结果如下:");
		for (int i = 1; i <= 4; i++) {			// 分别求出5的1-4次方
			ob = five;
			System.out.println("The five power of " + i + " is "
					+ ob.getNextVal());
		}
		System.out.println("\n求5的n的倍数如下:");
		for (int i = 1; i <= 5; i++) {			// 分别求出5的1-5倍数的值
			fiOb.val = i;
			System.out.println("The five Mult of " + i + " is "
					+ fiOb.getNextVal());
		}
	}
}
interface Number {
	int getNextVal(); 					// 获取下一个返回值
	void setInitVal(); 					// 初始化变量start、val
	void setMult(int x); 					// 设置某点的数值,即给val重新赋值。
}
class PowerOfFive implements Number {		// 求5的n次方
	int start;							// 进行运算的数字
	int val;							// 结果
	PowerOfFive() {
		start = 1;
		val = 1;
	}
	// 实现接口中定义的所有方法
	public int getNextVal() {
		val *= 5;
		return val;
	}
	public void setInitVal() {
		start = 1;
		val = 1;
	}
	public void setMult(int n) {
		start = n;
		val = n;
	}
}
class MultOfFive implements Number {	// 求5的n倍的值
	int start;
	int val;
	MultOfFive() {
		start = 1;
		val = 1;
	}
	//实现接口中定义的所有方法
	public int getNextVal() {
		setMult(val);				// 调用setMult方法,重新设置运算数
		val *= 5;
		return val;
	}
	public void setInitVal() {
		start = 1;
		val = 1;
	}
	public void setMult(int n) {
		start = n;
		val = n;
	}
}

 

  实例184 商品订单

package Chapter10.inter;
public class Order {
	public static void main(String[] args) {
		String[][] str = new String[][] { // 创建二维数组存储订单表格中的数据
			{ "name\t|", "mater\t|", "style\t\t|", "color\t|", "size\t\t|",
						"price\t|" },
				{ "blouses", "cotton", "long sleeve", "black", "free size",
						"36.8" },
				{ "T-shirt", "cotton", "long sleeve", "black", "free size",
						"25.5" },
				{ "sweater", "Knit", "long sleeve", "purple", "free size",
						"40.9" },
				{ "trouser", "cotton", "straight pant", "gray", "Two feet",
						"20.0" } };
		GoodsOrder goods = new en_Order(str); 			// 接口变量引用类对象
		OrderForm form1 = new OrderForm(goods); 		// 创建表格实例
		System.out.println("货号20090821-01的订单如下:[语言:English]");
		form1.display("en"); // 显示英文状态下的商品信息
	System.out.println("—————————————————————————————————————————————————————————————————");
		System.out.println("\n货号20090821-02的订单如下:[语言:中文]");
		Clothes clo1 = new Clothes("韩版瑞丽女式衬衫", "纯棉", "长袖", "黑色", 36.8, "均码");// 创建衣服对象用一维数组存储
		Clothes clo2 = new Clothes("韩版两件套t恤", "纯棉", "长袖", "黑色", 25.5, "均码");
		Clothes clo3 = new Clothes("毛衣针织衫", "针织", "长袖", "紫色", 40.9, "均码");
		Clothes clo4 = new Clothes("运动休闲长裤", "85%棉", "直筒裤", "灰色", 20.0, "2尺");
		Clothes clo5 = new Clothes("韩版雪纺连衣裙", "雪纺", "七分袖", "浅粉色", 35.8, "均码");
		Clothes clo6 = new Clothes("韩版男式长袖外套", "棉", "套头", "枣红色", 47.2, "ML");
		Clothes[] clothes = { clo1, clo2, clo3, clo4, clo5, clo6 }; // 创建衣服数组,将创建好的衣服对象放入数组
		GoodsOrder goods1 = new zh_Order(clothes); // 接口变量引用类对象
		OrderForm form2 = new OrderForm(goods1); // 创建订单表格实例
		form2.display("zh"); // 显示中文状态下的商品信息
	System.out.println("—————————————————————————————————————————————————————————");
	}
}
class Clothes { // 衣服类
	private String material; // 衣服材料
	private String color; // 衣服颜色
	private String style; // 衣服款式
	private double price; // 衣服价格
	private String size;// 衣服尺码
	private String name;// 衣服名称
	// 构造方法为成员变量赋初始值
	public Clothes(String name, String material, String color, String style,
			double price, String size) {
		super();
		this.material = material;
		this.color = color;
		this.style = style;
		this.price = price;
		this.size = size;
		this.name = name;
	}
	// 对private成员变量的封装
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String getMaterial() {
		return material;
	}
	public void setMaterial(String material) {
		this.material = material;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getSize() {
		return size;
	}
	public void setSize(String size) {
		this.size = size;
	}
	public String getStyle() {
		return style;
	}
	public void setStyle(String style) {
		this.style = style;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
interface GoodsOrder { 					// 定义输出二维表的接口
	public int getFormCol(); 				// 获得表格的列数
	public int getFormRow();				// 获得表格的行数
	public String getValue(int row, int col); 	// 获得指定的某行某列的值
	public String getColName(int col); 		// 获得指定的列名
}
class en_Order implements GoodsOrder { 	// 定义一个英文订单类实现接口
	String[][] clothes; 					// 定义一个二维数组
	public en_Order(String[][] clothes) { 		// 带参数的构造方法
		this.clothes = clothes;
	}
	public String getColName(int col) { 		// 获得指定的列名
		return clothes[0][col];
	}
	public int getFormCol() { 				// 获得表格的列数
		return clothes[0].length;
	}
	public int getFormRow() { 			// 获得表格的行数
		return clothes.length - 1;
	}
	public String getValue(int row, int col) { 	// 获得指定的某行某列的值
		return clothes[row + 1][col];
	}
}
class zh_Order implements GoodsOrder { 	// 定义一个中文订单类实现接口
	private Clothes[] clothes;
	public zh_Order(Clothes[] clothes) { 		// 带参数的构造方法
		this.clothes = clothes;
	}
	public String getColName(int col) {		// 根据列的序号显示表头的内容
		switch (col) {
		case 0:
			return "名称\t\t|";
		case 1:
			return "质地\t|";
		case 2:
			return "颜色\t|";
		case 3:
			return "款式\t|";
		case 4:
			return "尺码\t|";
		case 5:
			return "价格\t|";
		default:
			return null;
		}
	}
	public int getFormCol() {		// 设置列数
		return 6;
	}
	public int getFormRow() {
		return clothes.length;
	}
	public String getValue(int row, int col) {
		switch (col) {			// 将衣服对象中的商品信息取出
		case 0:
			return clothes[row].getName();
		case 1:
			return clothes[row].getMaterial();
		case 2:
			return clothes[row].getStyle();
		case 3:
			return clothes[row].getColor();
		case 4:
			return clothes[row].getSize();
		case 5:
			return clothes[row].getPrice() + "";
		default:
			return null;
		}
	}
}
class OrderForm { 						// 订单表格类
	private GoodsOrder goods;
	public OrderForm(GoodsOrder goods) { 	// 带参数的构造方法
		this.goods = goods;
	}
	public void display(String str) { 			// 显示格式和取值
	if(str.equals("en"))System.out.println("—————————————————————————————————————————————————————————————————");
	else System.out.println("—————————————————————————————————————————————————————————");
		for (int i = 0; i < goods.getFormCol(); i++) { // 循环显示列名
			System.out.print(goods.getColName(i));
		}
		System.out.println();
		for (int i = 0; i < goods.getFormRow(); i++) { // 循环显示行信息
			if (str.equals("en"))
	System.out.println("—————————————————————————————————————————————————————————————————");
	else System.out.println("—————————————————————————————————————————————————————————");
			for (int j = 0; j < goods.getFormCol(); j++) {// 循环显示列信息
				System.out.print(goods.getValue(i, j) + "\t|");
			}
			System.out.println();
		}
	}
}

 

  实例185 多功能排序

package Chapter10.inter;
public class SortTest {
	public static void printValue(int[] number) {// 打印数组元素的内容
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return;
		}
		for (int i = 0; i < number.length; i++) {// 用for循环将数据元素取出
			System.out.print(number[i] + " ");
		}
		System.out.println();
	}
	public static void main(String[] args) {
		int[] number = new int[] { 53, 10, 2, 4, 54, 14, -15, -2, 0 };// 创建一个int型数组并初始化
		System.out.print("使用\"选择排序法\"排序前的数组:");
		printValue(number);// 调用printValue方法将number数组的元素打印出
		Sort test = new SelectionSort();// 创建SelectionSort对象
		// 调用实现父类接口中的两个方法:ascSort和descSort
		System.out.print("\t升序排序的结果:");
		printValue(test.ascSort(number));
		System.out.print("\t降序排序的结果:");
		printValue(test.descSort(number));
		System.out.print("\n使用\"冒泡排序法\"排序前的数组:");
		printValue(number);// 调用printValue方法将number数组的元素打印出
		test = new BubbleSort();// 创建BubbleSort对象
		// 调用实现父类接口中的两个方法:ascSort和descSort
		System.out.print("\t升序排序的结果:");
		printValue(test.ascSort(number));
		System.out.print("\t降序排序的结果:");
		printValue(test.descSort(number));
		System.out.print("\n使用\"快速排序法\"排序前的数组:");
		printValue(number);// 调用printValue方法将number数组的元素打印出
		test = new QuickSort();// 创建QuickSort对象
		// 调用实现父类接口中的两个方法:ascSort和descSort
		System.out.print("\t升序排序的结果:");
		printValue(test.ascSort(number));
		System.out.print("\t降序排序的结果:");
		printValue(test.descSort(number));
	}
}
interface Sort {// 排序接口
	// 在接口中定义了两个抽象方法
	public int[] ascSort(int[] number);// 对整型数组按升序排序,并返回排好序的数组
	public int[] descSort(int[] number);// 对整型数组按降序排序,并返回排好序的数组
}
// 选择排序法
class SelectionSort implements Sort {// 创建一个类实现接口
	public int[] ascSort(int[] number) {// 升序排序法
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return null;
		}
		int[] copyArray = (int[]) number.clone();// 调用数组的clone方法,直接克隆一个数组。
		int size = copyArray.length;
		// 从头遍历数组元素
		for (int i = 0; i < size; i++) {
			// 遍历下标为i之后的元素
			for (int j = i; j < size; j++) {
				// 如果数组前面的值比后面的值大,则交换位置
				if (copyArray[i] > copyArray[j]) {
					exchange(copyArray, i, j);
				}
			}
		}
		return copyArray;
	}
	public int[] descSort(int[] number) {// 降序排序法
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return null;
		}
		int[] copyArray = (int[]) number.clone();// 调用数组的clone方法,直接克隆一个数组。
		int size = copyArray.length;
		// 从头遍历数组元素
		for (int i = 0; i < size; i++) {
			// 遍历下标为i之后的元素
			for (int j = i; j < size; j++) {
				// 如果数组前面的值比后面的值小,则交换位置
				if (copyArray[i] < copyArray[j]) {
					exchange(copyArray, i, j);
				}
			}
		}
		return copyArray;
	}
	// 交换数组中下标的值,其中:from源下标, to目标下标
	public void exchange(int[] toArray, int from, int to) {
		int temp = toArray[from];
		toArray[from] = toArray[to];
		toArray[to] = temp;
	}
}
// 冒泡排序法
class BubbleSort implements Sort {// 创建一个类去实现Sort接口
	SelectionSort ss = new SelectionSort();// 创建SelectionSort类对象
	public int[] ascSort(int[] number) {// 升序排序法
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return null;
		}
		int[] copyArray = (int[]) number.clone();// 调用数组的clone方法,直接克隆一个数组。
		// 用当前的数组元素和在它之后的所有元素进行比较
		for (int i = 0; i < copyArray.length; i++) {
			for (int j = i + 1; j < copyArray.length; j++) {
				// 将下标为i的数与下标为j的数进行比较,如果后面的元素小于前面的则进行元素交换
				if (copyArray[i] > copyArray[j]) {
					ss.exchange(copyArray, i, j);
				}
			}
		}
		return copyArray;
	}
	public int[] descSort(int[] number) {// 降序排序法
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return null;
		}
		int[] copyArray = (int[]) number.clone();// 调用数组的clone方法,直接克隆一个数组。
		// 用当前的数组元素和在它之后的所有元素进行比较
		for (int i = 0; i < copyArray.length; i++) {
			for (int j = i + 1; j < copyArray.length; j++) {
				// 将下标为i的数与下标为j的数进行比较,如果后面的元素大于前面的则进行元素交换
				if (copyArray[i] < copyArray[j]) {
					ss.exchange(copyArray, i, j);
				}
			}
		}
		return copyArray;
	}
}
// 快速排序法
class QuickSort implements Sort {// 创建一个类去实现Sort接口
	SelectionSort ss = new SelectionSort();// 创建SelectionSort类对象
	public int[] ascSort(int[] number) {// 升序排序法
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return null;
		}
		int[] copyArray = (int[]) number.clone();// 调用数组的clone方法,直接克隆一个数组。
		return this.asc_quickSort(copyArray, 0, copyArray.length - 1);// 调用asc_quickSort方法
	}
	public int[] descSort(int[] number) {// 降序排序法
		if (number == null) {// 如果该数组是空的则返回,不执行下面的语句。
			return null;
		}
		int[] copyArray = (int[]) number.clone();// 调用数组的clone方法,直接克隆一个数组。
		return this.desc_quickSort(copyArray, 0, copyArray.length - 1);// 调用desc_quickSort方法
	}
	// 用递归的方式实现快速升序排序。copyArray:待排序的数组,begin:开始下标,end:终止下标
	private int[] asc_quickSort(int[] copyArray, int begin, int end) {
		if (begin < end) {
			int n = asc_partition(copyArray, begin, end);
			asc_quickSort(copyArray, begin, n - 1);
			asc_quickSort(copyArray, n + 1, end);
		}
		return copyArray;
	}
	// 用递归的方式实现快速降序排序。copyArray:待排序的数组,begin:开始下标,end:终止下标
	private int[] desc_quickSort(int[] copyArray, int begin, int end) {
		if (begin < end) {
			int n = desc_partition(copyArray, begin, end);
			desc_quickSort(copyArray, begin, n - 1);
			desc_quickSort(copyArray, n + 1, end);
		}
		return copyArray;
	}
	// 升序排序。以数组中第一个元素为标准,把大于该数的元素往后排,把小于该数的元素往前排
	private int asc_partition(int[] copyArray, int first, int last) {
		int temp = copyArray[first];
		int n = first;
		for (int i = first + 1; i <= last; i++) {
			if (copyArray[i] < temp) {
				n++;
				ss.exchange(copyArray, n, i);
			}
		}
		ss.exchange(copyArray, first, n);
		return n;
	}
	// 降序排序。以数组中第一个元素为标准,把大于该数的元素往前排,把小于该数的元素往后排
	private int desc_partition(int[] copyArray, int first, int last) {
		int temp = copyArray[first];
		int n = first;
		for (int i = first + 1; i <= last; i++) {
			if (copyArray[i] > temp) {
				n++;
				ss.exchange(copyArray, n, i);
			}
		}
		ss.exchange(copyArray, first, n);
		return n;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值