JavaRush /Java 博客 /Random-ZH /Java 中 10 种常用的数组技术
theGrass
第 24 级
Саратов

Java 中 10 种常用的数组技术

已在 Random-ZH 群组中发布
Java 中常用的数组 技术有以下 10 种。他们在 Stack Overflow(一个关于编程的问答系统)上排名最高。 Java 中 10 种常用的数组技术 - 1
  1. 数组声明

    String[] aArray = new String[5];
    String[] bArray = {"a","b","c", "d", "e"};
    String[] cArray = new String[]{"a","b","c","d","e"};
  2. Java中的数组输出

    int[] intArray = { 1, 2, 3, 4, 5 };
    String intArrayString = Arrays.toString(intArray);
    
    // print directly will print reference value
    System.out.println(intArray);
    // [I@7150bd4d
    
    System.out.println(intArrayString);
    // [1, 2, 3, 4, 5]
  3. 从数组创建ArrayList

    String[] stringArray = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
    System.out.println(arrayList);
    // [a, b, c, d, e]
  4. 检查数组中的特定值

    String[] stringArray = { "a", "b", "c", "d", "e" };
    boolean b = Arrays.asList(stringArray).contains("a");
    System.out.println(b);
    // true
  5. 合并两个数组

    int[] intArray = { 1, 2, 3, 4, 5 };
    int[] intArray2 = { 6, 7, 8, 9, 10 };
    // Apache Commons Lang library
    int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
  6. 在一行中声明一个数组

    method(new String[]{"a", "b", "c", "d", "e"});
  7. 将数组元素连接成字符串

    // containing the provided list of elements
    // Apache common lang
    String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
    System.out.println(j);
    // a, b, c
  8. 转换ArrayList为数组

    String[] stringArray = { "a", "b", "c", "d", "e" };
    ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
    String[] stringArr = new String[arrayList.size()];
    arrayList.toArray(stringArr);
    for (String s : stringArr)
    	System.out.println(s);
  9. 将数组转换为集合 ( Set)

    Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
    System.out.println(set);
    //[d, e, b, c, a]
  10. 返回一个数组,其中元素的顺序相反

    int[] intArray = { 1, 2, 3, 4, 5 };
    ArrayUtils.reverse(intArray);
    System.out.println(Arrays.toString(intArray));
    //[5, 4, 3, 2, 1]
  11. 从数组中删除一个元素

    int[] intArray = { 1, 2, 3, 4, 5 };
    int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
    System.out.println(Arrays.toString(removed));

    还有一件事 -byte基于类型的值创建一个类型的数组int(大约ByteBuffer,选择其中的 4 个字节并放入数字int8,然后将所有这些 (0, 0, 0, 8) 转换为数组byte使用调用的类型array()

    byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
    
    for (byte t : bytes) {
       System.out.format("0x%x ", t);
    }
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION