You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

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.

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

Strings in Java
 String s = "spam";
 char c = s.charAt(1);
Strings in Python
 S = "spam"
 c = S[1] # c = "p"
  • No labels