Array to arraylist android java

Create ArrayList from array

Yep. And in the (most common) case where you just want a list, the new ArrayList call is unecessary as well.

@Calum and @Pool — as noted below in Alex Miller’s answer, using Arrays.asList(array) without passing it into a new ArrayList object will fix the size of the list. One of the more common reasons to use an ArrayList is to be able to dynamically change its size, and your suggestion would prevent this.

Arrays.asList() is a horrible function, and you should never just use its return value as is. It breaks the List template, so always use it in the form indicated here, even if it does seem redundant. Good answer.

@Adam Please study the javadoc for java.util.List. The contract for add allows them to throw an UnsupportedOperationException. docs.oracle.com/javase/7/docs/api/java/util/… Admittedly, from an object-oriented perspective it is not very nice that many times you have to know the concrete implementation in order to use a collection — this was a pragmatic design choice in order to keep the framework simple.

Element[] array = new Element[] < new Element(1), new Element(2), new Element(3) >; 

The simplest answer is to do:

List list = Arrays.asList(array); 

This will work fine. But some caveats:

  1. The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you’ll need to wrap it in a new ArrayList . Otherwise you’ll get an UnsupportedOperationException .
  2. The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.

Wrapping in a new ArrayList() will cause all elements of the fixed size list to be iterated and added to the new ArrayList so is O(n).

To clarify, Arrays.asList() creates a java.util.Arrays.ArrayList (static nested class in java.util.Arrays ), not a java.util.ArrayList .

(old thread, but just 2 cents as none mention Guava or other libs and some other details)

If You Can, Use Guava

It’s worth pointing out the Guava way, which greatly simplifies these shenanigans:

Usage

For an Immutable List

Use the ImmutableList class and its of() and copyOf() factory methods (elements can’t be null) :

List il = ImmutableList.of("string", "elements"); // from varargs List il = ImmutableList.copyOf(aStringArray); // from array 

For A Mutable List

Use the Lists class and its newArrayList() factory methods:

List l1 = Lists.newArrayList(anotherListOrCollection); // from collection List l2 = Lists.newArrayList(aStringArray); // from array List l3 = Lists.newArrayList("or", "string", "elements"); // from varargs 

Please also note the similar methods for other data structures in other classes, for instance in Sets .

Why Guava?

The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator.

Читайте также:  Нераздельный пробел html nbsp

But it’s not the only reason (and Java 7 isn’t everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections.

If You Can’t.

For an Immutable List

Use the JDK’s Arrays class and its asList() factory method, wrapped with a Collections.unmodifiableList() :

List l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements)); List l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2")); 

Note that the returned type for asList() is a List using a concrete ArrayList implementation, but it is NOT java.util.ArrayList . It’s an inner type, which emulates an ArrayList but actually directly references the passed array and makes it «write through» (modifications are reflected in the array).

It forbids modifications through some of the List API’s methods by way of simply extending an AbstractList (so, adding or removing elements is unsupported), however it allows calls to set() to override elements. Thus this list isn’t truly immutable and a call to asList() should be wrapped with Collections.unmodifiableList() .

See the next step if you need a mutable list.

For a Mutable List

Same as above, but wrapped with an actual java.util.ArrayList :

List l1 = new ArrayList(Arrays.asList(array)); // Java 1.5 to 1.6 List l1b = new ArrayList<>(Arrays.asList(array)); // Java 1.7+ List l2 = new ArrayList(Arrays.asList("a", "b")); // Java 1.5 to 1.6 List l2b = new ArrayList<>(Arrays.asList("a", "b")); // Java 1.7+ 

For Educational Purposes: The Good ol’ Manual Way

// for Java 1.5+ static List arrayToList(final T[] array) < final Listl = new ArrayList(array.length); for (final T s : array) < l.add(s); >return (l); > // for Java < 1.5 (no generics, no compile-time type-safety, boo!) static List arrayToList(final Object[] array) < final List l = new ArrayList(array.length); for (int i = 0; i < array.length; i++) < l.add(array[i]); >return (l); > 

Источник

How to convert array to arraylist in android?

This example demonstrates How to convert array to arraylist in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

In the above code, we have taken name and record number as Edit text, when user click on save button it will store the data into arraylist. Click on refresh button to get the changes of listview.

Step 3 − Add the following code to src/MainActivity.java

package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class MainActivity extends AppCompatActivity < EditText name; ArrayAdapter arrayAdapter; ArrayListarray_list; Set set = new HashSet(); private ListView listView; @Override protected void onCreate(Bundle readdInstanceState) < super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); array_list = new ArrayList(); array_list.ensureCapacity(20); name = findViewById(R.id.name); listView = findViewById(R.id.listView); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); >>); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < if (!name.getText().toString().isEmpty()) < set.add(name.getText().toString()); array_list.clear(); if (array_list.isEmpty()) < String[] array = new String[]; ArrayList list = new ArrayList(Arrays.asList(array)); array_list.addAll(list); array_list.addAll(set); Collections.sort(array_list, new Comparator() < @Override public int compare(String o1, String o2) < return o1.compareTo(o2); >>); array_list.trimToSize(); arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); > else < listView.setVisibility(View.GONE); >Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); > else < name.setError("Enter NAME"); >> >); > >

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Читайте также:  Java spring rest post

In the above result, we are inserting array items.

Click here to download the project code

Источник

How to Convert a Java Array to ArrayList

In this tutorial, we’ll be converting an array into a more versatile ArrayList in Java.

Arrays are simple and provide the basic functionality of grouping together a collection of objects or primitive data types. However, arrays are also limited — their size is fixed and even basic operations like adding new items at the beginning or rearranging elements can get complicated.

Thankfully, the Collections Framework introduced us to many very useful implementations of List s, Set s, and Queue s.

One of these is the ArrayList , a really versatile and popular implementation of a List .

An ArrayList ‘s constructor will accept any Collection . We can get creative with the type of collection we pass into it.

Arrays.asList()

Let’s start off with the simplest form of conversion. The Arrays helper class has a lot of useful methods. The asList() method returns the contents of the array in a List :

Employee emp1 = new Employee("John"); Employee emp2 = new Employee("Sarah"); Employee emp3 = new Employee("Lily"); Employee[] array = new Employee[]; List list = Arrays.asList(array); System.out.println(list); 

This will result in a List implementation ( ArrayList ) to be populated with emp1 , emp2 and emp3 . Running this code results in:

[Employee, Employee, Employee] 

new ArrayList<>(Arrays.asList())

A better approach than just assigning the return value of the helper method is to pass the return value into a new ArrayList<>() . This is the standard approach used by most people.

This is because the asList() method is backed by the original array.

If you change the original array, the list will change as well. Also, asList() returns a fixed size, since it’s backed by the fixed array. Operations that would expand or shrink the list would return a UnsupportedOperationException .

To avoid these, we’ll apply the features of an ArrayList by passing the returned value of asList() to the constructor:

Employee[] array = new Employee[]; List list = new ArrayList<>(Arrays.asList(array)); System.out.println(list); 
[Employee, Employee, Employee] 

new ArrayList<>(List.of())

Since Java 9, you can skip initializing an array itself and passing it down into the constructor. You can use List.of() and pass individual elements:

List list = new ArrayList<>(List.of(emp1, emp2, emp3)); System.out.println(list); 
[Employee, Employee, Employee] 

Collections.addAll()

The Collections class offers a myriad of useful helper methods and amongst them is the addAll() method. It accepts a Collection and a vararg of elements and joins them up.

It’s very versatile and can be used with many collection/vararg flavors. We’re using an ArrayList and an array:

Employee[] array = new Employee[]; List list = new ArrayList<>(); Collections.addAll(list, array); System.out.println(list); 
[Employee, Employee, Employee] 

Collectors.toList()

If you’re working with streams, rather than regular collections, you can collect the elements of the stream and pack them into a list via toList() :

Employee[] array = new Employee[]; List list = Stream.of(array).collect(Collectors.toList()); System.out.println(list); 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

[Employee, Employee, Employee] 

Collectors.toCollection()

Similarly, you can use the toCollection() method to collect streams into different collections. In our case, we’ll supply the ArrayList::new method reference into it, though you could supply other references as well:

Employee[] array = new Employee[]; List list = Stream.of(array) .collect(Collectors.toCollection(ArrayList::new)); System.out.println(list); 
[Employee, Employee, Employee] 

Lists.newArrayList()

Similar to the Arrays.asList() helper class and method, Google’s Guava project introduced us to the Lists helper class. The Lists helper class provides the newArrayList() method:

Employee[] array = new Employee[]; List list = Lists.newArrayList(array); 

Now, the key takeaway of this approach was that you don’t need to specify the type when initializing an ArrayList . This was really useful when you’d have a > list.

Читайте также:  Css and html templates with code

However, as Java 7 removed the need to explicitly set the type in the diamond operator, this became obsolete.

Conclusion

There are numerous ways to convert an array to an ArrayList in Java. These span from calling helper methods to streaming the array and collecting the elements.

Источник

Assigning an array to an ArrayList in Java

Note that you aren’t technically assigning an array to a List (well, you can’t do that), but I think this is the end result you are looking for.

The Arrays class contains an asList method which you can use as follows:

String[] words = . ; List wordList = Arrays.asList(words); 

This returns a fixed-size list of strings encapsulated by some private type that implements the List interface. @NullUserException’s answer is the best if you need an instance of java.util.ArrayList that is mutable.

Richard, just wanted to know that why is the above list becoming fixed-size? Can’t I further add another element to the same list in the next line.. like wordList.add(anotherStringElement);

That’s the defined behaviour of the asList method. As @NullUserException points out you should convert to an ArrayList [ArrayList aList = new ArrayList(Arrays.asList(words)] in order to obtain an ArrayList that you can add further items to.

If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:

String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = . then List allEds = new ArrayList(); Collections.addAll(allEds, array1); 
 int[] ar = ; ArrayList list = new ArrayList<>(); for(int i:ar) < list.add(new Integer(i)); >System.out.println(list.toString()); // prints : [10, 20, 20, 10, 10, 30, 50, 10, 20] 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью