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

2016/6/7

Help with Lists

sengst sengst

2016/6/7

#
How do I create a new list that contains multiple integers? thanks! A line of code would also be greatly apreciated.
SPower SPower

2016/6/7

#
If by 'list' you mean an array, you simply create one the way you do this in Java:
1
2
3
4
5
6
7
int[] integerArray = new int[5]; // an empty array that could store 5 ints
int[] anotherArray = new int[]{ 1, 2, 10, 42 }; // an array with 4 specified elements
 
// example usage:
integerArray[0] = 5*7;
integerArray[1] = 2 *integerArray[0];
integerArray[2] = 10 -anotherArray[2];
If, however, you're referring to the List object as found in the java.util package, you'd use the Integer class to store the integers:
1
2
3
4
5
List<Integer> integerList = new ArrayList<Integer>();
// example usage:
integerList.add(5); // if I'm correct, the 5 will automatically be 'interpreted' as new Integer(5)
integerList.add(99);
int firstValue = integerList.get(0).intValue();
You'd still have to import List and ArrayList, though, at the top of your 'file':
1
2
import java.util.List;
import java.util.ArrayList;
The only real reason you would want to use a List is if you badly wanted to have a variable size; an array can't change size, you'd have to create a new array for that. Using an array is the easiest (and least intensive) method, however.
sengst sengst

2016/6/7

#
Thank you very much for your help!
You need to login to post a reply.