Java ArrayList type issue - java

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");

Related

explanation of List<String> how it is being used in the code

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";

How to dynamically change a list value to another list in Java or Groovy

For Example, I have a list like below,
list1 = ["a","b","c"] now i want to add value to the list[1] index and that index will be another list like,
list2 = ["w","x","y"]
The output will be ["a",["b","w","x","y"],"c"] I don't want to replace 1 index
Is it possible?
Your base list contains two types: String and List<String>
You can create a list as your base list in java but is not a good idea because you are mixing types. That is a bad practice. You should avoid raw types.
You could use a helper method like :
private static List mergeIntoList(List source, List listToAdd, int index) {
List innerList = new ArrayList(listToAdd);
innerList.add(0, source.get(index));
List mergedList = new ArrayList(source);
mergedList.set(index, innerList);
return mergedList;
}
Exemple:
List source = Arrays.asList("a", "b", "c");
List listToAdd = Arrays.asList("w", "x", "y");
System.out.println(mergeIntoList(source, listToAdd, 1));
output: [a, [b, w, x, y], c]
But I repeat, you should avoid raw types, so this solution is not recommended
It's possible, but not very type safe (=don't do it). You could use a List and then add your values, which could be any type of Object (Integer String... or another List).
When retrieving the Objects you would need to check what type they are with instanceof and then cast them.
In java it is not possible taking type of list1 as String.
Type of list1 seems String and you are adding another list into list1 which is not correct.
But it is possible taking type list1 as Object
List<Object> list1=new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<Object> innerlist=new ArrayList<>(); //Inner List
list1.add(innerlist);
However it is not recommended way.
You can add value to a specific index as below
List list = new ArrayList();
List l1 = new ArrayList();
l1.add("3");
l1.add("4");
list.add("1");
list.add("5");
list.add(1, l1);
Please make sure that index in the list size, otherwise will get the IndexOutOfBoundsException
Please try below logic
public List replaceIndex(List original, List replace, int index) {
Object object = original.remove(index);
replace.add(0, object);
original.add(index, replace);
return original;
}

Java Array to ArrayList to Array

I have an array name "asset" with 4 number.
I then converted it to be stored in arraylist.
Then with the arraylist copy to another array.
Is this algorithm correct?
After adding 5 the array should be able to show 5 number now
List assetList = new ArrayList();
String[] asset = {"1", "2", "3", "4"};
Collections.addAll(assetList, asset);
assetList.add("5");
String [] aListToArray = new String[assetList.size()];
aListToArray.toArray(aListToArray);
You need to change this line
aListToArray.toArray(aListToArray); // aListToArray to aListToArray itself? This would have given a compilation error
to this
assetList.toArray(aListToArray); // assetList to aListToArray is what you need.
Use just Arrays.asList(asset);
You can make some simplifications:
List assetList = new ArrayList();
String[] asset = {"1", "2", "3", "4"};
assetList.addAll(asset);
assetList.add("5");
String [] aListToArray = assetList.toArray(aListToArray);
Overall, the code is correct. However if you want to have a "dynamic array", or a collection of items that changes in size, then don't bother trying to keep something in array form. An arraylist will work fine.

How to correctly specify a list in java

I am using Eclipse Juno and Java.
I want to create a list and then store that list in another list so I can pass the list of lists to the server side. I have tried:
ArrayList<T> listAccountAndCubs = new ArrayList<Comparable>();
listAccountAndCubs.add(accountId);
listAccountAndCubs.add(sqlDateArchived);
However, I can not get the values "T" and "Comparable" correct. I tried "String" however that does not work for storing the date.
Once the above is correct how do I set up the list to contain "listAccountAndCubs"?
Thanks for any assistance,
Glyn
this is how you can create a list
List<String> l = new ArrayList<String>();
this is how you can create list of list
List<List<Comparable>> listOfList = new ArrayList<List<Comparable>>();
listOfList.add(new ArrayList<Comparable>());
...
Sounds like you want something like this
List<List<String>> listAccountAndCubs = new ArrayList<List<String>>();
I would recomment using Google Guava library to clean the syntax a bit
List<List<String>> listAccountAndCubs = Lists.newArrayList();
List<ArrayList<Comparable>> listAccountAndCubs = new ArrayList<>();
or
List<String> l1=new ArrayList<>();
List<List<String>> l2=new ArrayList<>();
l1.add("a");
l2.add(l1);
If I understand you crrectly you want to have a list of Strings, and store this in another list?
List<String> sl = new ArrayList<String>();
List<List<String>>sls = new ArrayList<List<String>>();
sls.add(sl);
sl.add("String 1");
The value "T" is just a placeholder for the type, as the list is a generic interface, which can take any arbitrary object.
If you want to create a list of unspecified types, you would use
List<?>list = new ArrayList<?>();
Then you can add untyped objects to it, but in your case this is not neccessary.
Instead you can of course also create a list of comparables. Like this:
List<Comparable<String>>list = new ArrayList<Comparable<String>>();

ArrayList in java

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);

Categories

Resources