JavaRush /בלוג Java /Random-HE /10 טכניקות מערך נפוצות ב-Java
theGrass
רָמָה
Саратов

10 טכניקות מערך נפוצות ב-Java

פורסם בקבוצה
10 הטריקים הבאים של המערך ב-Java נמצאים בשימוש נפוץ. יש להם את הדירוג הגבוה ביותר ב-Stack Overflow, מערכת של שאלות ותשובות על תכנות. 10 טכניקות מערך נפוצות ב-Java - 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