How to add new elements to an array?

后端 未结 18 1694
误落风尘
误落风尘 2020-11-22 04:55

I have the following code:

String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + \"=1\");
where.append(ContactsContract.Contacts.IN_VISIB         


        
相关标签:
18条回答
  • 2020-11-22 05:18

    You need to use a Collection List. You cannot re-dimension an array.

    0 讨论(0)
  • 2020-11-22 05:21

    There is no method append() on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.

    List<String> where = new ArrayList<String>();
    where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
    where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");
    

    Or if you are really keen to use an array:

    String[] where = new String[]{
        ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
        ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
    };
    

    but then this is a fixed size and no elements can be added.

    0 讨论(0)
  • 2020-11-22 05:22

    I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size. You have to use an ArrayList or a Vector or any other dynamic structure.

    0 讨论(0)
  • 2020-11-22 05:22

    You can simply do this:

    System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);
    
    0 讨论(0)
  • 2020-11-22 05:25

    Apache Commons Lang has

    T[] t = ArrayUtils.add( initialArray, newitem );
    

    it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.

    0 讨论(0)
  • 2020-11-22 05:25

    There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.

    String[] array1 = new String[]{"one", "two"};
    String[] array2 = new String[]{"three"};
    String[] array = new String[array1.length + array2.length];
    System.arraycopy(array1, 0, array, 0, array1.length);
    System.arraycopy(array2, 0, array, array1.length, array2.length);
    
    0 讨论(0)
提交回复
热议问题