Python's list is essentially an array - Java has two similar data structures. First is an array, which is a list with only a set number of 'slots', and second is an ArrayList, which is the closest to Python's list. Notice that for both you need to declare what type of variables it's going to be holding.
Declaration
Arrays in Java and Python are both displayed using curly brackets, the difference is that they are called Iists in Python.
Code Block |
---|
language | java |
---|
title | Arrays in Java |
---|
| int[] A = new int[]{3,5,7};
A[0] = 1; // A = {1,5,8}
A = new int[5]; // A = {0,0,0,0,0} |
| Code Block |
---|
language | py |
---|
title | Arrays in Python |
---|
| A = ["spam", "baked beans", "sausage", "spam"]
B = A[0:2] # B = ["spam", "baked beans"]
B[1] = "spam" # B = ["spam", "spam"]
B = B + ["Eric"] # B = ["spam�, "spam", "Eric"] |
|
In Java, Strings are not arrays. You need to use String methods to access individual characters, while in Python, Strings can be treated as immutable arrays of characters.
Code Block |
---|
language | java |
---|
title | Strings in Java |
---|
| String s = "spam";
char c = s.charAt(1); |
| Code Block |
---|
language | py |
---|
title | Strings in Python |
---|
| S = "spam"
c = S[1] # c = "p" |
|