Remove Item from ArrayList

In this specific case, you should remove the elements in descending order. First index 5, then 3, then 1. This will remove the elements from the list without undesirable side effects. for (int j = i.length-1; j >= 0; j–) { list.remove(i[j]); }

List to ArrayList conversion issue

Cast works where the actual instance of the list is an ArrayList. If it is, say, a Vector (which is another extension of List) it will throw a ClassCastException. The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined … Read more

java howto ArrayList push, pop, shift, and unshift

ArrayList is unique in its naming standards. Here are the equivalencies: Array.push -> ArrayList.add(Object o); // Append the list Array.pop -> ArrayList.remove(int index); // Remove list[index] Array.shift -> ArrayList.remove(0); // Remove first element Array.unshift -> ArrayList.add(int index, Object o); // Prepend the list Note that unshift does not remove an element, but instead adds one … Read more

How can I convert ArrayList to ArrayList?

Since this is actually not a list of strings, the easiest way is to loop over it and convert each item into a new list of strings yourself: List<String> strings = list.stream() .map(object -> Objects.toString(object, null)) .toList(); Or when you’re not on Java 16 yet: List<String> strings = list.stream() .map(object -> Objects.toString(object, null)) .collect(Collectors.toList()); Or … Read more

Why is Java’s AbstractList’s removeRange() method protected?

Yes, because that’s not how you remove a range from outside code. Instead, do this: list.subList(start, end).clear(); This actually calls removeRange behind the scenes.† The OP asks why removeRange is not part of the List public API. The reason is described in Item 40 of Effective Java 2nd ed, and I quote it here: There … Read more

From Arraylist to Array

Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away! ArrayList<Integer> foo = new ArrayList<Integer>(); foo.add(1); foo.add(1); foo.add(2); foo.add(3); foo.add(5); Integer[] bar = foo.toArray(new Integer[foo.size()]); System.out.println(“bar.length … Read more

Retrieving a random item from ArrayList [duplicate]

anyItem is a method and the System.out.println call is after your return statement so that won’t compile anyway since it is unreachable. Might want to re-write it like: import java.util.ArrayList; import java.util.Random; public class Catalogue { private Random randomGenerator; private ArrayList<Item> catalogue; public Catalogue() { catalogue = new ArrayList<Item>(); randomGenerator = new Random(); } public … Read more