现在的位置: 首页 > 综合 > 正文

16、StringBuffer类与包装类、java数组

2018年02月06日 ⁄ 综合 ⁄ 共 2281字 ⁄ 字号 评论关闭

字符串String是个常量,其对象一旦创建完毕就无法该改变,使用“+”进行拼接时,是生成了一个新的String对象,而不是向原有的String对象追加内容。字符串与任何其他原生数据类型变量相“+”,其他都先转换为字符串,然后相加。

StringBuffer初始化有16个字符长度,append()方法返回StringBuffer对象本身,toString()方法返回一个字符串。

1、包装类(Wrapper Class)。针对原生数据类型的包装。所有的包装类(8个)都位于java.lang包下。java中8个包装类分别是:Byte类、Short类、Long类、Float类、Double类、Character类和Boolean类。可以实现原生数据类型与包装类的双向转换。

2、数组(Array):相同类型数据的集合就叫做数组。如何定义数组:

type[] 变量名 = new type[数组中元素的个数];   或者   type 变量名[] = new type[]

int[]  a = new int[4];      int a[] = int[4];

数组中的元素索引是从0开始的,对于数组来说,最大的索引== 数组长度-1;

数组的三种定义与初始化:
public class ArrayTest
{
	public static void main(String[] args)
	{
		int[] a = new int[4];
		
		a[0] = 1;
		a[1] = 2;
		a[2] = 3;
		a[3] = 4;

		System.out.println(a[3]);

		int b[] = new int[2];

		b[0] = 1;
		b[1] = 2;

		int[] c = {1,2,3,4};

		System.out.println(c[2]);

		int[] d = new int[]{1,2,3,4};

	}
}

 3、java中每个数组都有一个length属性,表示数组的长度。length属性是public ,final,int的。数组长度一旦确定,就不能改变大小。

int[] a = new int[4];
a.lenght = 6;         //错误,length无法改变
int[] b = new int[4];
System.out.println(a[0]);   //打印0

没有赋初值,使用默认值。数组元素在内存中是连续存放的

int[] a = new int[10],其中a是一个引用,它指向了生成的数组对象的首地址,数组中每一个元素都是int类型,其中仅存放数据值本身。 

4、当是一个引用类型的数组时,假定定义了一个Person类,定义一个Person数组:Person[]  p = new Person[3];

5、二维数组:二维数组是一种平面的二维结构。本质上是数组的数组。二维数组的定义方式:

Type[][] a = new type[2][3];

java允许定义不规整的二维数组。 

int [][] a = new int[3][];

a[0] = new int[2];

a[1] = new int[3];

a[2] = new int[1];

二维数组初始化:

int[][] a = new int[][]{{1,2,3}{4,5}{6,7,8,9}};

6、关于交换

public class Swap1
{
	public static void swap(char[] ch,char c)
	{
		ch[0] = 'B';
		c ='D';
	}

	public static void swapInt(int[] i)
	{
		int temp = i[0];
		i[0] = i[1];
		i[1] = temp;
	}
	public static void main(String[] args)
	{
		char[] ch ={'A','C'};

		Swap1.swap(ch,ch[1]);

		for(int i = 0;i < ch.length;i++)
		{
		
		System.out.println(ch[i]);
		}

		int[] i ={1,2};

		Swap1.swapInt(i);
		
		for(int j = 0;j < i.length;j++)
		{
		
		System.out.println(i[j]);
		}

	}
}

7、如果定义了一个接口  interface I  {}

则I[] i = new I[2];是正确的。

8、java.util.Arrays类提供了大量数组方法共使用,这些方法都是静态的(static),可以直接通过类名加点的形式使用,就是Arrays.methods()方式使用。

9、java.lang.System类提供了很多静态数组方法,如arraycopy()等。

10、三维数组:int[][][] a = new int[2][3][4];

11、冒泡排序

public class BollList
{
	public static void bollList(int[] a)
	{
		for(int i = 0; i < a.length-1; i++)
		{
			boolean change = true;

			for(int k = 0; k < a.length - i -1; k++)
			{
				if(a[k] > a[k+1])
				{
					int temp = a[k+1];
					a[k+1] = a[k];
					a[k] = temp;

					change = false;
				}
			}
			
			if(change == true)
			{
				break;
			}
			for(int h = 0;h < a.length;h++)
			{
				System.out.print(a[h] + "  ");
			}
			System.out.println();
			
		}
	}
	
	public static void main(String[] args)
	{
		int[] a = new int[]{2,4,7,9,8};

		BollList.bollList(a);

		for(int i = 0; i < a.length; i++)
		{
			System.out.println(a[i]);
		}
	}
}

 

抱歉!评论已关闭.