黑马程序员技术交流社区

标题: 关于数组 [打印本页]

作者: 王杰wj    时间: 2015-6-15 17:17
标题: 关于数组
1、数组(Array):相同类型数据的集合。命名规则:type[]变量名 = new type[数组中的元素个数];
   例如:int[] a = new int[10];数组内的元素索引是从0开始,最大的索引为数组长度减去1。
2、数组有两种类型的赋值方法例如:int[] a = {1,2,3,4};或者int a = new int[]{1,2,3,4}。
3、Java中的每个数组都有一个名为length的属性表示数组的长度,length属性是public、final、int
   的,一旦确定就不能改变其大小。
4、int[] a = new int[10],其中a是一个引用,它指向了生成的数组对象的首地址,数组中每个元素
   都是int类型,其中仅存放数据值本身。
5、二维数组:是一种平面的二维结构,本质上是数组的数组,定义方式:type[][]a = new type[2][2]
6、生成不规则的二维数组:type[][] a = new type;其中i必须有参数值。给二维数组赋值{{第一行的 数组}{第二行的数组}{第三行的数组}}。
7、调用二维数组内的参数值:
   for(int i = 0;i < a.length;i++)
   {
             for(int j = 0;j < a[i].length;j++)
              {
                        System.out.println(a[i][j]);
             }
   }  
8、比较两个数组是否一样:
   import java.util.Arrays;
   public class Toequal()
   {
            public static void main(String[] args)
              {
                     int[] a = new int[]{1,2,3,4};
                      int[] b = new int[]{4,5,6};
                     System.out.println(Arrays.equals(a,b));
             }
   }
   如果返回值为false说明两个数组的参数值不同,如果为true说明相同。
9、使用二分查找查询数组内的某个数的索引(带查找的数组必须要有序)
   public static int go(int[] a,int value)
   {
           int low = 0;
           int high = a.length-1;
           while(low <= high)
          {
                   int middle = (low + high)/2;
                   if(value == a[middle])
                  {
                           return middle;
                  }
                  else if(value < a[middle])
                  {
                           high = middle - 1;
                  }
                  if(value > a[middle])
                  {
                           low = middle + 1;
                  }
           }
           return -1;
   }
10、冒泡排序
public class Test
{
        public static void ass(int[] array)
       {
                for(int i = 0;i < array.length-1;i++)
                 {
                         for(int j = 0;j < array.length-i-1;j++)
                         {
                                    if(array[j] > array[j+1])
                                  {
                                         int b = array[j];
                                        array[j] = array[j+1];
                                        array[j+1] = b;
                                  }
                          }
                   }
                   for(int x = 0;x < array.length;i++)
                   {
                          System.out.println(a[i]);
                   }
            }
           public static void main(String[] args)
          {
                      int[] array = {4,7,8,9,2,3};
                     ass(array)
            }
}      

作者: 耀阳圣尊    时间: 2015-6-15 17:51
总结的很不错




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2