Java数组详解

数组

数组,就是相同数据类型的元素按一定顺序排列的集合,就是把有限个类型相同的变量用一个名字命名,然后用编号区分他们的变量的集合,这个名字称为数组名,编号称为下标。

动态初始化数组

 int[] arrs=new int[5];
   arrs[0]=1;
   arrs[1]=1;
   arrs[2]=1;
   arrs[3]=1;

静态初始化数组

  int[] arrs={1,2,3,4,5};
  int[] arrs1=new int[]{1,2,3,4,4};

获取数组长度

int[] arrs={1,2,3,4,5};//数组长度为5
int arrLength=arrs.length;
System.out.println("数组长度为:"+arrLength);

遍历数组

for循环遍历

String[] arr=new String[]{"Java","C#","C++","C","Ruby"};
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);//遍历输出
}

增强for循环遍历

String[] arr=new String[]{"Java","C#","C++","C","Ruby"};
        for(String s:arr){
            System.out.println("输出编程语言:"+s);
        }

数组常用技巧

数组转List集合


String[] arr=new String[]{"Java","C#","C++","C","Ruby"};
        //数组转List集合
List<String> arrList=new ArrayList<String>(Arrays.asList(arr));

数组转Set集合

String[] arr=new String[]{"Java","C#","C++","C","Ruby"};
        //数组转set集合
Set<String> arrList=new HashSet<String>(Arrays.asList(arr));

判断数组是否包含某值

String[] arr=new String[]{"Java","C#","C++","C","Ruby"};
        //判断数组中是否包含某值
boolean b=Arrays.asList(arr).contains("C#");

数组输出

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    System.out.println(Arrays.toString(intArray));
    //输出结果为:[1, 2, 3, 4, 5]

    String[] strArray = new String[] {"C#", "Java", "C++"};
    System.out.println(Arrays.deepToString(strArray));
    //输出结果为:[C#, Java, C++]

你可能感兴趣的:(JavaSE)