This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Assigning an array to an ArrayList in Java
I need to convert a String[] to an ArrayList<String> and I don't know how
File dir = new File(Environment.getExternalStorageDirectory() + "/dir/");
String[] filesOrig = dir.list();
Basically I would like to transform filesOrig into an ArrayList.
You can do the following:
String [] strings = new String [] {"1", "2" };
List<String> stringList = new ArrayList<String>(Arrays.asList(strings)); //new ArrayList is only needed if you absolutely need an ArrayList
Like this :
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
or
List myList = new ArrayList();
String[] words = {"000", "aaa", "bbb", "ccc", "ddd"};
Collections.addAll(myList, words);
List<String> list = Arrays.asList(array);
The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.
List myList = new ArrayList();
Collections.addAll(myList, filesOrig);
You can loop all of the array and add into ArrayList:
ArrayList<String> files = new ArrayList<String>(filesOrig.length);
for(String file: filesOrig) {
files.add(file);
}
Or use Arrays.asList(T... a) to do as the comment posted.
You can do something like
MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
Related
This question already has answers here:
What is the shortest way to initialize List of strings in java?
(7 answers)
Closed 3 years ago.
Is there a shorthand way (may be guava or any lib) to initialize a Java List like this?
List list = MagicListUtil.newArrayList(firstElement, moreElementsList);
Guava offers several possibilities
If you have arrays, use Lists.asList(...)
String first = "first";
String[] rest = { "second", "third" };
List<String> list = Lists.asList(first, rest);
If you have lists or other Iterables, use FluentIterable.of(...).append(...).toList():
String first = "first";
List<String> rest = Arrays.asList("second", "third");
List<String> list = FluentIterable.of(first).append(rest).toList();
But you can do that in Java 8 as well
Even though, it's way more verbose, but still...
With an array
String first = "first";
String[] rest = { "second", "third" };
List<String> list = Stream.concat(Stream.of(first), Arrays.stream(rest))
.collect(Collectors.toList());
With a Collection
String first = "first";
List<String> rest = Arrays.asList("second", "third");
List<String> list = Stream.concat(Stream.of(first), rest.stream())
.collect(Collectors.toList());
Yeah you can simply use the java.util.Arrays class for single and multiple elements.
List<String> strings = Arrays.asList("first", "second", "third");
You can use the java.util.Collections for a list with a single element.
List<String> strings = Collections.singletonList("first");
If you wanna copy list, you can do it by constructor like this
List<Float> oldList = new ArrayList<>();
List<Float> newList = new ArrayList<>(oldList);
public static void main(String a[]){
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
I was looking for the explanation of the code
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
this line means that we are declaring a variable strArr of string type and in the array we are declaring 5 variables is that correct
Then I am unable to clearly understand second line
List<String> strList = Arrays.asList(strArr);
is strList an object of List<String>?
With the below code you are converting your String array to a fixed size list.
List<String> strList = Arrays.asList(strArr);
While converting an Array to a List. You can perform all operation of List to your newly created fixed size list. Exmaple Sorting a List as below.
Collection.sort(strList);
But with the above code you cannot add element into your list. While adding element in list it will throw you an exception. Sample code as below.
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
strList.add("Spring"); // This line will throw exception
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
If you want to add element to your list you have to convert your String Array to List as below.
List<String> strList = new ArrayList<String>(Arrays.asList(strArr));
Hope this will help you to understand it
Arrays.asList() is a static util for java. It creates a List copying the values from your array of strings (or any kind of primitive/object).
You can check the documentation on docs.oracle. The benefit of a List is that the size is variable, so you can add or remove elements (in short, it has no fixed size) while an array has a fixed size. This is true for List(Mutable list by default) unless you use an Immutable List which has a fixed size like an array.
Arrays.asList(T... arr) is a static method, sort of a utility, that takes an array as input and returns a List<T> backed by the input array. So, yes strList is a List.
To answer your question in the comments about "backed by":
From the Javadoc: "Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)".
So, the list is backed by the array in the sense that all changes made to the contents of the list will be reflected in the array. Example:
String[] a = new String[] {"1", "2", "3"};
List<String> l = Arrays.asList(a);
l.set(0, "0");
assert a[0] == "0";
This question already has answers here:
Add ArrayList to another ArrayList in java
(6 answers)
Closed 6 years ago.
I have a 2D arraylist which I want to fill it with several 1D arraylists. My code is the following:
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
while (ts2.next()) {
list.add( ts2.getString("userName");
list.add(ts2.getString("userId"));
array.add(list);
list.clear();
}
I have noticed that list.clear() deletes the elements from the list however also deletes the element from the array. In the end, both array and list are empty. How can I add list in array and clear the list after array.add(list)
You can clone the list:
array.add(list.clone());
Or you can instantiate the list object within the loop itself:
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
while (ts2.next()) {
ArrayList<String> list = new ArrayList<String>();
list.add( ts2.getString("userName");
list.add(ts2.getString("userId"));
array.add(list);
}
Then you wouldn't even need to clear it.
You can do this:
ArrayList<String[]> arr = new ArrayList<String[]>();
String[] str = new String[2];
while (ts2.next()) {
str[0] = ts2.getString("userName");
str[1] = ts2.getString("userId");
arr.add(str);
}
if you would an arraylist also:
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>();
while (ts2.next()) {
ArrayList<String> arrString = new ArrayList<String>();
arrString.add(ts2.getString("userName"));
arrString.add(ts2.getString("userId"));
arr.add(arrString);
}
You can create a new instance of ArrayList<> to be added in the existing one.
while (ts2.next()) {
List<String> list = new ArrayList<>();
list.add(ts2.getString("userName"));
list.add(ts2.getString("userId"));
array.add(list);
}
However the better approach is to map these values into a new instance of a class.
List<MyClass> = new ArrayList<>();
while (ts2.next()) {
MyClass i = new MyClass(ts2.getString("userName"), ts2.getString("userId"));
array.add(i);
}
I am new in Java.
Now I want to generate an ArrayList containing some values.
"Circle","blue","red","yellow","1","2","3","4"
How can I code this. I found some tutorial from internet. Only int or string accepted? How about mix? Could someone should me the code that how to do this?
Thanks!
List<String> list = Arrays.asList("Circle", "blue", "red", "yellow", "1", "2", "3", "4");
If you want to mix types, you'd need a List<Object>, and to remove the "" around the numbers. The example you show is all strings.
Once you start mixing types, you need to check the type when you're consuming the list, which may or may not be appropriate.
ArrayList<String> al = new ArrayList();
al.add("Circle");
al.add("blue");
al.add("red");
al.add("yellow");
al.add("1");
al.add("2");
al.add("3");
al.add("4");
here is a simple tutorial http://www.java-samples.com/showtutorial.php?tutorialid=234
or you can do this as well
String[] words = {"Circle", "blue", "red", "yellow", "1", "2", "3", "4"};
List<String> wordList = Arrays.asList(words);
List<Object> list = new ArrayList<Object>();
t.add("string");
t.add(5);
Or
List<Object> list = Arrays.asList("string", 5);
Or
List<Object> list = new ArrayList<Object>()
{{
add("string");
add(5);
}};
You only have one type for one list, some code for creating a list containing only Strings could be:
ArrayList<String> list = new ArrayList<String>();
//add my text as the first element
list.add("my text");
For a list with only ints you would have Integer instead of String in the example.
If you want to store "1","2","3","4" as string you could use
ArrayList<String> list = new ArrayList<String>();
Collections.addAll("Circle","blue","red","yellow","1","2","3","4");
You can not store int in any collection.However If you want to store "1","2","3","4" as Integer along with strings you could use
ArrayList<Object> list = new ArrayList<Object>();
Collections.addAll("Circle","blue","red","yellow",1,2,3,4);
Autoboxing will takecare of converting int to Integer
You many need to be extra careful while using ArrayList<Object>.
In Java, it's not recommended (although it's possible) to mix different types in a list of objects. So, for storing a list of Strings you would do this:
ArrayList<String> stringList = new ArrayList<String>();
And then add them:
stringList.add("Circle");
stringList.add("blue");
stringList.add("red");
stringList.add("yellow");
stringList.add("1");
stringList.add("2");
stringList.add("3");
stringList.add("4");
ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
How can I add veri2 to veri1 like one element? I mean, if I call veri.get(0), it returns veri2.
You should declare your list as a list of string arrays, not a list of strings:
List<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
veri1.add(veri2);
Note that in general it is better to declare your list as List instead of ArrayList, as this leaves you the freedom to switch to a different list implementation later.
You should use the List interface and generics (for Java >= 1.5). Depending on what you want to do you can use this:
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
List<String> veri1 = new ArrayList<String>();
veri1.addAll(Arrays.asList(veri2)); // Java 6
List<String[]> veri3 = new ArrayList<String[]>();
veri3.add(veri2);
You can't actually do this.
veri2 is an array of strings, veri1 is an arraylist of individual strings
Thus, doing veri1.get(0) should return a single string, not an array of strings.
I just saw (due to fm), that you have an ArrayList<String>. You can do:
ArrayList veri1 = new ArrayList();
veri1.add(veri2)
or
ArrayList<String[]> veri1 = new ArrayList<String[]>();
veri1.add(veri2)
You can also make ver1 a List, which gives you flexibility in changing implementations.
It all depends on whether or not you want your ArrayList to be of one type or if you need it to hold multiple types.
If you just need it to hold String arrays throughout your code, declare as stated above:
ArrayList<String[]> list1 = new ArrayList<String[]>();
then just add the String array to it as follows:
list1.add(stringArray);
If you want it to be dynamic, declare it with the object type:
ArrayList<Object> anythingGoes = new ArrayList<Object>();
and then you can add anything later on as well:
anythingGoes.add(stringArray);
anythingGoes.add(myAge);
anythingGoes.add(myName);
I think you mean this:
import java.util.Arrays;
ArrayList<String> veri1 = new ArrayList<String>();
String[] veri2 = {"Fatih", "Ferhat", "Furkan"};
veri1.addAll(Arrays.asList(veri2);
You pretty much just need to add the array to the ArrayList.
ArrayList<String[]> veri1 = new ArrayList<String[]>();
String[] veri2 = {"a", "b", "c"};
veri1.add(veri2);
System.out.println(veri1.size());
for(String[] sArray : veri1)
for(String s : sArray)
System.out.println(s);