Java基础知识回顾之数组简介Java基础知识回顾之数组与方法参数的传递
Java基础知识回顾之自定义数组

说明

前面介绍了数组的定义,这里就通过不同的代码实例来介绍数组与方法参数的传递内容。

数组引用传递

数组中内容当传递到一个方法中的时候,传递的一个栈内存的指向(也就是说传递的是堆内容)。传递到另外一个方法中的数据改变之后,原始的数组内容已经被修改。即:数组在方法中传递的是引用地址。

public class TestDemo {

    public static void main(String[] args) {
        int data[] = new int[]{2, 3, 4};    // 静态初始化数组变量
        changeValue(data);                  //  对数组进行操作

        // 循环输出
        for (int i=0; i< data.length; i++){
            System.out.print( data[i] + "\t");      // 输出结果:4	6	8
        }
    }

    public static void changeValue(int temp[]){
        for (int i=0; i< temp.length; i++){
            temp[i] *= 2;       //  将数组的值 乘以 2 并且保存
        }
    }
}

通过一个方法返回数组

通过一个方法体返回一个数组对象。

public class TestDemo {
	
	public static void main(String[] args) {
		
		// 可以通过一个方法直接获取一个数组
		int data[] = init();
		
		// 数组可以直接使用 length 取得长度
		System.out.println(init().length);		
	}
	
	//  方法返回一个数组
	public static int[] init() {
		return new int[] {1, 2, 3};
	}

}

冒泡排序

数组的排序操作在笔试之中经常会被问到,下面是升序排序的基本原理:

原始数据:      2、 1、 9、 0、 5、 3、 7、 6、 8
第一次排序:    1、 2、 0、 5、 3、 7、 6、 8、 9
第二次排序:    1、 0、 2、 3、 5、 6、 7、 8、 9
第三次排序:     0、 1、 2、 3、 5、 6、 7、 8、 9
public class BubbleSort {

	public static void main(String[] args) {
		
		int arrays[] = new int[] {2, 1, 9, 0, 5, 3, 7, 6, 8}; 
		print(arrays);
		
		sort(arrays);
		
		System.out.println();
		print(arrays);
	}
	
	public static void sort(int temps[]) {
		// 控制整个循环,防止出现 下标越界
		for(int i=0, len=temps.length; i<len; i++) {
			// 循环比较
			for(int j=0, length= temps.length-1; j<length; j++) {
				// 交换位置
				if( temps[j] > temps[j+1] ){
					int value = temps[j];
					temps[j] = temps[j+1];
					temps[j+1] = value;
				}
			}
		}
	}
	
	public static void print(int temps[]) {
		for(int i=0, len=temps.length; i<len; i++) {
			System.out.print(temps[i]+ "\t" );
		}
	}
}

可以直接使用 Arrays.sort(data[])

import java.util.Arrays;

public class TestDemo {
	
	public static void main(String[] args) {
        int data[] = new int[]{9, 3, 4, 1};    // 静态初始化数组变量

        Arrays.sort(data);		// 对数组进行排序
        
        // 循环输出
        for (int i=0; i< data.length; i++){
            System.out.print( data[i] + "\t");      // 输出结果:1	3	4	9	
        }
    }
}

对象数组

在某些特定的情况下,我们可能需要使用到对象数组。即声明的时候,就是声明出一个对象的数组出来 Book book[] = new Book[3];

class Book{
	String title ;
	double price;
	
	Book(){}
	
	Book(String title, double price){
		this.title = title;
		this.price = price;
	}
	
	public String getInfo() {
		return "书名:" + this.title + ",价格为:" + this.price;
	}
}

public class TestDemo {
	
	public static void main(String[] args) {
		Book book[] = new Book[3];	//  声明一个三个长度的数组
		
		// 对 book 数组进行填充
		book[0] = new Book("Java", 6.0d);
		book[1] = new Book("Android", 8.0d);
		book[2] = new Book("Python", 7.0d);
		
		for (int i = 0, len=book.length; i<len; i++) {
			//  循环输出内容
			System.out.println(book[i].getInfo());
		}
    }
}