Skip to content
Advertisement

Tag: arraylist

java howto ArrayList push, pop, shift, and unshift

I’ve determined that a Java ArrayList.add is similar to a JavaScript Array.push I’m stuck on finding ArrayList functions similar to the following Array.pop Array.shift Array.unshift I’m leaning toward ArrayList.remove[At] Answer ArrayList is unique in its naming standards. Here are the equivalencies: Note that unshift does not remove an element, but instead adds one to the list. Also note that corner-case

Sort ArrayList of strings by length

I want to order an ArrayList of strings by length, but not just in numeric order. Say for example, the list contains these words: They need to be ordered by their difference in length to a special string, for example: So the final list would look like this (difference in brackets): Answer Use a custom comparator: Then sort the list

Remove multiple elements from ArrayList

I have a bunch of indexes and I want to remove elements at these indexes from an ArrayList. I can’t do a simple sequence of remove()s because the elements are shifted after each removal. How do I solve this? Answer Sort the indices in descending order and then remove them one by one. If you do that, there’s no way

Moving items around in an ArrayList

I’ve been playing around with ArrayLists. What I’m trying to achieve is a method to do something like this: I’m trying to be able to move items up in the list, unless it is already at the top in which case it will stay the same. For example, if item 3 was moved the list would be: From my small

Java convert Arraylist to float[]

How I can do that? I have an arraylist, with float elements. (Arraylist <Float>) it is not working. cannot cast from Object[] to float[] Answer Loop over it yourself. The nullcheck is mandatory to avoid NullPointerException because a Float (an object) can be null while a float (a primitive) cannot be null at all. In case you’re on Java 8

What are the differences between ArrayList and Vector?

What are the differences between the two data structures ArrayList and Vector, and where should you use each of them? Answer Differences Vectors are synchronized, ArrayLists are not. Data Growth Methods Use ArrayLists if there is no specific requirement to use Vectors. Synchronization If multiple threads access an ArrayList concurrently then we must externally synchronize the block of code which

How to set arrayList size as null?

Why the size of the arrayList choice is 5 when all the elements have been set to null Answer Because the ArrayList still contains 5 Objects. They are null, but they are objects, thus present in the list! You can empty the ArrayList, by calling choice.clear();

Advertisement