SPG
SPG

Reputation: 6197

Java ArrayList type issue

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!

Upvotes: 1

Views: 1034

Answers (6)

hiran
hiran

Reputation: 53

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>.

Upvotes: 1

pahan
pahan

Reputation: 2453

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

Upvotes: 1

lfxgroove
lfxgroove

Reputation: 3908

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.

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117589

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

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235994

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

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160181

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.

Upvotes: 2

Related Questions