In java to remove an element in an array can you s

2019-09-19 13:58发布

I am trying to make a remove method that works on an array implementation of a list. Can I set the the duplicate element to null to remove it? Assuming that the list is in order.

ArrayList a = new ArrayList[];

public void removeduplicates(){

    for(a[i].equals(a[i+1]){

        a[i+1] = null;

    }
    a[i+1] = a[i];
}

9条回答
Deceive 欺骗
2楼-- · 2019-09-19 14:31

No, an array element containing a null is still there, it just doesn't contain any useful value.

You could try moving every element from further down in the list up by 1 element to fill the gap, then you have a gap at the end of the array - the array will not shrink from doing this!

If you're doing this a lot, you can use System.arraycopy() to do this packing operation quickly.

查看更多
该账号已被封号
3楼-- · 2019-09-19 14:34

Use ArrayList.remove(int index).

  if(a[i].equals(foo()))
     a.remove(i)

But be careful when using for-loops and removing objects in arrays.

http://java.sun.com/j2se/1.3/docs/api/java/util/ArrayList.html

查看更多
神经病院院长
4楼-- · 2019-09-19 14:35

The straight-forward answer to your question is that setting an array or ArrayList element to null gives you a null entry in the array or ArrayList. This is not the same thing as removing the element. If just means that a[i] or a.get(i) will return null rather than the original element.

The code in the question is garbled. If you are going to use an ArrayList, the simplisitic solution would be something like this:

ArrayList a = new ArrayList();

public void removeduplicates() {
    for (int i = 0; i < a.size() - 1; ) {
        if (a.get(i).equals(a.get(i + 1)) {
            a.remove(i);
        } else {
            i++;
        }
    }
}

but in the worst case, that is O(N**2) because each call to remove copies all elements at indexes greater than the current value of i.

If you want to improve the performance, do something like this:

public ArrayList removeduplicates() {
    ArrayList res = new ArrayList(a.size());
    if (a.size() == 0) {
        return res;
    }
    res.add(a.get(0));
    for (int i = 1; i < a.size(); i++) {
        if (!a.get(i - 1).equals(a.get(i)) {
            res.add(a.get(i));
        }
    }
    return res;
}

(This is a quick hack. I'm sure it could be tidied up.)

查看更多
smile是对你的礼貌
5楼-- · 2019-09-19 14:38

No you can't remove an element from an array, as in making it shorter. Java arrays are fixed-size. You need to use an ArrayList for that.

If you set an element to null, the array will still have the same size, but with a null reference at that point.

 // Let's say a = [0,1,2,3,4] (Integer[])
 a[2] = null;
 // Now a = [0,1,null,3,4]
查看更多
该账号已被封号
6楼-- · 2019-09-19 14:39

Is this a homework question?

Your problem is analogous to the stream processing program uniq: Preserve -- by way of copying -- any element that doesn't match the one before it. It only removes all duplicates if the sequence is sorted. Otherwise, it only removes contiguous duplicates. That means you need to buffer at most one element (even if by reference) to use as a comparison predicate when deciding whether to keep an element occurring later in the sequence.

The only special case is the first element. As it should never match any preceding element, you can try to initialize your buffered "previous" element to some value that's out of the domain of the sequence type, or you can special-case your iteration with a "first element" flag or explicitly copy the first element outside the iteration -- minding the case where the sequence is empty, too.

Note that I did not propose you provide this operation as a destructive in-place algorithm. That would only be appropriate with a structure like a linked list with constant-time overhead for removing an element. As others note here, removing an element from an array or vector involves shuffling down successor elements to "fill the hole", which is of time complexity n in the number of successors.

查看更多
Animai°情兽
7楼-- · 2019-09-19 14:41

Your code example was quite confusing. With ArrayList[] you showed an array of ArrayList objects.

Assuming that you're talking about just the java.util.ArrayList, then the most easy way to get rid of duplicates is to use a java.util.Set instead, as mentioned by others. If you really want to have, startwith, or end up with a List for some reasons then do:

List withDuplicates = new ArrayList() {{ add("foo"); add("bar"); add("waa"); add("foo"); add("bar"); }}; // Would rather have used Arrays#asList() here, but OK.
List withoutDuplicates = new ArrayList(new LinkedHashSet(withDuplicates));
System.out.println(withoutDuplicates); // [foo, bar, waa]

The LinkedHashSet is chosen here because it maintains the ordering. If you don't worry about the ordering, a HashSet is faster. But if you actually want to have it sorted, a TreeSet may be more of value.

On the other hand, if you're talking about a real array and you want to filter duplicates out of this without help of the (great) Collections framework, then you'd need to create another array and add items one by one to it while you check if the array doesn't already contain the to-be-added item. Here's a basic example (without help of Arrays.sort() and Arrays.binarySearch() which would have eased the task more, but then you would end up with a sorted array):

String[] array1 = new String[] {"foo", "bar", "foo", "waa", "bar"};
String[] array2 = new String[0];

loop:for (String array1item : array1) {
    for (String array2item : array2) {
        if (array1item.equals(array2item)) {
            continue loop;
        }
    }
    int length = array2.length;
    String[] temp = new String[length + 1];
    System.arraycopy(array2, 0, temp, 0, length);
    array2 = temp;
    array2[length] = array1item;
}

System.out.println(Arrays.toString(array2)); // [foo, bar, waa]

Hope this gives new insights.

查看更多
登录 后发表回答