Initial size for the ArrayList

You can set the initial size for an ArrayList by doing ArrayList<Integer> arr=new ArrayList<Integer>(10); However, you can’t do arr.add(5, 10); because it causes an out of bounds exception. What is the use of setting an initial size if you can’t access the space you allocated? The add function is defined as add(int index, Object element) … Read more

How does a ArrayList’s contains() method evaluate objects?

Say I create one object and add it to my ArrayList. If I then create another object with exactly the same constructor input, will the contains() method evaluate the two objects to be the same? Assume the constructor doesn’t do anything funny with the input, and the variables stored in both objects are identical. ArrayList<Thing> … Read more

What is the Simplest Way to Reverse an ArrayList?

What is the simplest way to reverse this ArrayList? ArrayList<Integer> aList = new ArrayList<>(); //Add elements to ArrayList object aList.add(“1”); aList.add(“2”); aList.add(“3”); aList.add(“4”); aList.add(“5”); while (aList.listIterator().hasPrevious()) Log.d(“reverse”, “” + aList.listIterator().previous()); 12 Answers 12

How to quickly and conveniently create a one element arraylist [duplicate]

This question already has answers here: Initialization of an ArrayList in one line (33 answers) Closed 5 years ago. Is there a Utility method somewhere that can do this in 1 line? I can’t find it anywhere in Collections, or List. public List<String> stringToOneElementList(String s) { List<String> list = new ArrayList<String>(); list.add(s); return list; } … Read more

How to avoid “ConcurrentModificationException” while removing elements from `ArrayList` while iterating it? [duplicate]

This question already has answers here: Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop (30 answers) Closed 7 years ago. I’m trying to remove some elements from an ArrayList while iterating it like this: for (String str : myArrayList) { if (someCondition) { myArrayList.remove(str); } } Of course, I get a … Read more

How to sort a List/ArrayList?

I have a List of doubles in java and I want to sort ArrayList in descending order. Input ArrayList is as below: List<Double> testList = new ArrayList(); testList.add(0.5); testList.add(0.2); testList.add(0.9); testList.add(0.1); testList.add(0.1); testList.add(0.1); testList.add(0.54); testList.add(0.71); testList.add(0.71); testList.add(0.71); testList.add(0.92); testList.add(0.12); testList.add(0.65); testList.add(0.34); testList.add(0.62); The out put should be like this 0.92 0.9 0.71 0.71 0.71 0.65 … Read more