This site requires JavaScript, please enable it in your browser!
Greenfoot back
sengst
sengst wrote ...

2016/5/31

Adding objects to a List

sengst sengst

2016/5/31

#
I need to add an object to a list, however I do not know how. Can somebody help me?
danpost danpost

2016/6/1

#
sengst wrote...
I need to add an object to a list, however I do not know how. Can somebody help me?
See this page of the java API documentation.
sengst sengst

2016/6/1

#
What is the line of code needed to use that?
danpost danpost

2016/6/1

#
Well, you need these import lines:
1
2
import java.util.List;
import java.util.ArrayList;
Then, you need to create a List object:
1
List<Object> list = new ArrayList<Object>();
Then you can add objects to the list:
1
2
3
4
5
6
7
8
Actor actor = new Actor(){}; // some actor to be added to List
list.add(actor);
String text = "abcdefg";
list.add(text);
World world = this;
list.add(world);
int n = 125;
list.add((Integer)n);
The objects added to this list are just random to show different types being added and the type of objects is wide open because I use 'Object' as the type of elements that can be added to the list.
sengst sengst

2016/6/3

#
Thank you very much! You have been a great help.
You need to login to post a reply.