建站学 - 轻松建站从此开始!

建站学-个人建站指南,网页制作,网站设计,网站制作教程

当前位置: 建站学 > 网站开发 > Java教程 >

java中靠什么实现指针的功能

时间:2019-08-13 14:13来源:PHP中文网 作者:猪哥 点击:
可以利用接口与类实现指针功能,应先定义一个接口,然后在接口中声明要调用的方法,接着实现这个接口(不同的功能实现,例如一个升序排列,一个降序排序),最后把这个实现类的一个对象作为参数给调用程序,调动程序通过这个参数来调用指定的函数。
首先来看一下什么是C语言中的指针,字面上理解就是一个类似实现定位功能的结构。指针最重要的功能,就是实现回调函数,所谓回调函数,就是指让函数先在某处注册,而它将在稍后某个需要的时候被调用。回调函数一般用于截获消息,获取系统信息或处理异步事件。

如何实现类似于C语言中函数指针的功能

在Java语言中没有指针的概念,可以利用接口与类实现同样的效果,应先定义一个接口,然后在接口中声明要调用的方法,接着实现这个接口(不同的功能实现,例如一个升序排列,一个降序排序),最后把这个实现类的一个对象作为参数给调用程序,调动程序通过这个参数来调用指定的函数。

具体实现如下:

interface IntCompare
{
	public int cmp(int a,int b);
}

class Cmp1 implements IntCompare
{
	public int cmp(int a,int b)
	{
		if(a>b)
			return 1;
		else if(a<b)
			return -1;
		else 
			return 0;
	}
}

class Cmp2 implements IntCompare
{
	public int cmp(int a,int b)
	{
		if(a>b)
			return -1;
		else if(a<b)
			return 1;
		else
			return 0;
	}
}

class HelloWorld
{
	public static void main(String[] args)
	{
		int[] array1 = {7,3,19,40,4,7,1};
		insertSort(array1,new Cmp1());
		System.out.println("升序排列");
		for(int i=0;i<array1.length;i++)
		{
			System.out.print(array1[i]+" ");
		}
	
		System.out.println();
		int[] array2 = {7,3,19,40,4,7,1};
		insertSort(array2,new Cmp2());
		System.out.println("降序排列");
		for(int i =0;i<array2.length;i++)
		{
			System.out.print(array2[i]+" ");
		}
		
	}
									
	public static void insertSort(int[] a,IntCompare cmp)	
	{
		if(a!=null)
		{
			
			for(int i=1;i<a.length;i++)
			{
				int temp = a[i],j=i;
				if(cmp.cmp(a[j-1], temp)==1)    
				{
					while(j>=1&&cmp.cmp(a[j-1],temp)==1)	
					{
						a[j] = a[j-1];
						j--;
					}
				}
				a[j] = temp;
			}
			for(int i=1;i<a.length;i++)
			{
				int temp = a[i];
				int j = i-1;
				while(j>=0&&cmp.cmp(a[j], temp)==1)
				{
					a[j+1] = a[j];
					j--;
				}
				a[j+1] = temp;
			}
		}
	}
}
(责任编辑:admin)
织梦二维码生成器
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片