Skip to content

Commit

Permalink
Fixed issue code.google.com/p/google-gson/issues/detail?id=353 by add…
Browse files Browse the repository at this point in the history
…ing remove and contains methods in JsonArray
  • Loading branch information
inder123 committed Jul 2, 2014
1 parent 953ca1a commit 8f8bd3b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
31 changes: 31 additions & 0 deletions gson/src/main/java/com/google/gson/JsonArray.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,37 @@ public void addAll(JsonArray array) {
elements.addAll(array.elements);
}

/**
* Removes the first occurrence of the specified element from this array, if it is present.
* If the array does not contain the element, it is unchanged.
* @param element element to be removed from this array, if present
* @return true if this array contained the specified element, false otherwise
*/
public boolean remove(JsonElement element) {
return elements.remove(element);
}

/**
* Removes the element at the specified position in this array. Shifts any subsequent elements
* to the left (subtracts one from their indices). Returns the element that was removed from
* the array.
* @param index index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException if the specified index is outside the array bounds
*/
public JsonElement remove(int index) {
return elements.remove(index);
}

/**
* Returns true if this array contains the specified element.
* @return true if this array contains the specified element.
* @param element whose presence in this array is to be tested
*/
public boolean contains(JsonElement element) {
return elements.contains(element);
}

/**
* Returns the number of elements in the array.
*
Expand Down
20 changes: 19 additions & 1 deletion gson/src/test/java/com/google/gson/JsonArrayTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@

package com.google.gson;

import com.google.gson.common.MoreAsserts;
import junit.framework.TestCase;

import com.google.gson.common.MoreAsserts;

/**
* @author Jesse Wilson
*/
Expand Down Expand Up @@ -50,6 +51,23 @@ public void testEqualsNonEmptyArray() {
assertFalse(b.equals(a));
}

public void testRemove() {
JsonArray array = new JsonArray();
try {
array.remove(0);
fail();
} catch (IndexOutOfBoundsException expected) {}
JsonPrimitive a = new JsonPrimitive("a");
array.add(a);
assertTrue(array.remove(a));
assertFalse(array.contains(a));
array.add(a);
array.add(new JsonPrimitive("b"));
assertEquals("b", array.remove(1).getAsString());
assertEquals(1, array.size());
assertTrue(array.contains(a));
}

public void testDeepCopy() {
JsonArray original = new JsonArray();
JsonArray firstEntry = new JsonArray();
Expand Down

0 comments on commit 8f8bd3b

Please sign in to comment.