How to add element in List while iterating in java?

You can’t use a foreach statement for that. The foreach is using internally an iterator: The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator … Read more

ArrayList vs LinkedList from memory allocation perspective

LinkedList might allocate fewer entries, but those entries are astronomically more expensive than they’d be for ArrayList — enough that even the worst-case ArrayList is cheaper as far as memory is concerned. (FYI, I think you’ve got it wrong; ArrayList grows by 1.5x when it’s full, not 2x.) See e.g. https://github.com/DimitrisAndreou/memory-measurer/blob/master/ElementCostInDataStructures.txt : LinkedList consumes 24 … Read more

Convert ArrayList to String array in Android

Use the method “toArray()” ArrayList<String> mStringList= new ArrayList<String>(); mStringList.add(“ann”); mStringList.add(“john”); Object[] mStringArray = mStringList.toArray(); for(int i = 0; i < mStringArray.length ; i++){ Log.d(“string is”,(String)mStringArray[i]); } or you can do it like this: (mentioned in other answers) ArrayList<String> mStringList= new ArrayList<String>(); mStringList.add(“ann”); mStringList.add(“john”); String[] mStringArray = new String[mStringList.size()]; mStringArray = mStringList.toArray(mStringArray); for(int i = 0; … Read more

ArrayList’s custom Contains method

here’s some code that might demonstrate how it works out: import java.util.ArrayList; class A { private Long id; private String name; A(Long id){ this.id = id; } @Override public boolean equals(Object v) { boolean retVal = false; if (v instanceof A){ A ptr = (A) v; retVal = ptr.id.longValue() == this.id; } return retVal; } … Read more

How can I check if two ArrayList differ, I don’t care what’s changed

On the definition of “sameness” As Joachim noted, for most application, List.equals(Object o) definition works: Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. … Read more

casting Arrays.asList causing exception: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

For me (using Java 1.6.0_26), the first snippet gives the same exception as the second one. The reason is that the Arrays.asList(..) method does only return a List, not necessarily an ArrayList. Because you don’t really know what kind (or implementation of) of List that method returns, your cast to ArrayList<String> is not safe. The … Read more