1

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!

6 Answers 6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

1

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.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.