2019/07/05 08:26
【数组】: 引用数据类型(地址)
for-each不适用于数组遍历,因为没有索引
【数组浅复制】:
需要创建新的存储区域,并依次确定每隔元素的值
【元素交换位置】:
1.利用第三个变量交换数值,简单的方法。
int x =5,y=10; //定义两个变量
int temp = x; //定义第三临时变量temp并提取x值
x = y; //把y的值赋给x
y = temp; //然后把临时变量temp值赋给y
System.out.println(“x=”+x+“y=”+y);
2.可以用两个数求和然后相减的方式进行数据交换,弊端在于如果 x 和 y 的数值过大的话,超出 int 的值会损失精度。
int x =5,y=10; //定义两个变量
x = x + y; //x(15) = 5 + 10;
y = x - y; //y(5) = x(15) - 10;
x = x - y; //x(10) = x(15) - y(5)
System.out.println(“x=”+x+“y=”+y);
3.利用位运算的方式进行数据的交换,利用的思想原理是:一个数异或同一个数两次,结果还是那个数,而且不会超出int范围
int x =5,y=10; //定义两个变量
x = x^y;
y = x^y; //y=(xy)y
x = x^y; //x=(xy)x
System.out.println(“x=”+x+“y=”+y);
4.最为简单的,在打印输出的时候直接交换变量
int x =5,y=10; //定义两个变量
System.out.println(“x=”+y+“y=”+x); //直接在输出的时候交换
【数组的排序】: 比较 + 交换位置
1、确定首位元素的值
(1)选择:通过遍历,比较首位元素与其他每个元素,最终把最小的值放到了首位
int[] a = {8,25,65,4,36,98};
for(int i = 0; i < a.length-1; i++) {
//确定第i号格子的值
for(int j = i+1; j < a.length; j++) {
if(a[j] < a[i]) {
int temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
(2)冒泡:从远离首位的地方,比较相邻元素,通过交换最终把最小值放在了首位
2、反复地做第一步的事情,只管剩余元素
【数组排序之Arrays.sort(数组)】
java.util.Arrays它提供的所有方法都是静态的。类中的sort()方法,它可以直接将基本类型的数组进行排序
int[] a = {1,5,669,56,75};
Arrays.sort(a);
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
【数组排序之Comparable接口】
Arrays.sort(数组) 的参数如果是对象数组的话,那么它的执行会报异常,因为对象无法进行比较。异常信息也提示我们被排序的对象必须实现Comparable接口并实现其中的排序规则即
public int compareTo(Object o) 方法。
即继承关系是下面这样的形态
interface Comparable < T >
{
public int compareTo( T ); //返回值为“正整数,0,负整数”分别代表“大于、相等、小于”3种情况
}
class MyClass implements Comparable < MyClass >{
public int compareTo(MyClass one)//指定排序规则
{
//比如if( this.xxx > one.xxx) return ...;
}
}
示例
public class Student implements Comparable {
String name ;
int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int compareTo(Student o) //制定排序规则
{
if(this.age > o.age) return -1;
else if(this.age == o.age) return 0;
else return 1;
}
}
import java.util.Arrays;
public class TestArray {
public static void main(String[] args) {
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 20);
Student s3 = new Student("小明", 5);
Student s4 = new Student("Tom", 10);
Student[] ss = {s1,s2,s3,s4};
Arrays.sort(ss);
for( Student s:ss) {
System.out.println(s.name + s.age);
}
}
}
运行结果
李四20
张三18
Tom10
小明5
【多维数组】: 二维数组 --多维数组是数组的数组
二维数组定义:
1.数据类型[ ][ ] 数组名 = new int[ 一维数组个数][一维数组元素个数 ];
2.数据类型[ ][ ] 数组名 =new int[ 一维数组个数][一维数组元素个数 ]{ };
简写:数据类型[ ][ ] 数组名 = {{ },{ },{ },…};
为每个元素赋值:
二维数组遍历:
【对象数组】
Person[] ps = new Person[2];
ps[0] = new Person(“张三”, 23);
ps[1] = new Person(“李四”, 25);
或者定义为:
Person[] ps = new Person[]{ new Person(“张三”, 23),
new Person(“李四”, 25)};
简写:
Person[] ps = { new Person(“张三”, 23),
new Person(“李四”, 25)};