I'm trying to learn Java, more specifically I'm trying to learn a couple of differences when working with arrays and lists. Right now I'm trying to understand how I can implement this line list += [i]*i
in Java.
Sum = 5000
list = [0, 0]
x = 1
while len(list) < Sum:
list += [x]*x
x += 1
I've tried a lot of different methods but I can't seem to find a way. The results I get in Java with the methods I've tried are all wrong.
Directly translated (with the helpful utility function java.util.Collections.nCopies
) it becomes something like:
import java.util.*;
int Sum = 5000; //Following the naming convention in Java (and Python) "Sum" should be lowercase
ArrayList<Integer> list = new ArrayList<Integer>();
//Alternatively: List<Integer> list = new ArrayList<Integer>();
list.add(0);
list.add(0);
int x = 1;
while (list.size() < Sum) {
list.addAll(Collections.nCopies(x, x));
x += 1;
}
Use a combination of for loop, add method and a ArrayList data structure. It could look something like below.
List<Integer> nums = new ArrayList<>();
int x = 1;
while (condition){
for (int i=0; i<x; i++) {
nums.add(x);
}
x+=1
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.