PYTHON VS. JAVA: LISTS VS. ARRAYS
PYTHON VS. JAVA: LISTS VS. ARRAYS
Java arrays are similar to Python lists (stores a collection of values). Key differences:
Java arrays have a xed length which is set when constructing the array All elements in the array have the same type
A more minor difference: unlike Python, you can't use negative indices to fetch elements from a Java array.
1 / 6
An example of code using Java arrays:
// the data type integer array is represented as int[] int[] myArray; // this creates new array object with a size of 3 (can store 3 integers) myArray = new int[3]; myArray[0] = 207; // set first element to be the value 207 myArray[1] = myArray[0] + 1; // set second element to be the value 208 // alternative way to create array with values in it int[] anotherArray = {1, 2, 3}; // toString method returns string representation of an array System.out.println(Arrays.toString(myArray)); // two ways to use for loop to print an array's elements: for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]); } for (int item: anotherArray) {
System.out.println(item); }
2 / 6
SOME NOTES ON OBJECTS
Although all elements must have the same type, you can use inheritance to get around that. E.g., every object is a descendant of
class called Object in Java.
Object[] miscellany = new Object[5]; miscellany[0] = "Songbird";
Every primitive type has a "wrapper class" class. It lets you wrap up a value in an object. Perfect for times like this when you need an object.
miscellany[1] = new Integer(42);
3 / 6
ARRAYLIST
When you really don't know what size your array must be, you can use an ArrayList instead of the basic Java array. The ArrayList class is a resizable array, which can be found in the java.util package. Notes about ArrayList object:
an ArrayList size can change as needed (similar to Python list) all elements must still be of the same type the elements cannot be primitive data types to use ArrayList, you must import java.util.ArrayList
4 / 6
ARRAYLIST
What if I wanted an ArrayList of integers?? Yes, an ArrayList cannot store ints, doubles, booleans,
or any other primitive data type. Solution: Just use the equivalent wrapper class for the
primitive type you need.
5 / 6
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- java array of arrays example
- mutual fund vs index fund vs etf
- aerobic respiration vs anaerobic respiration vs fermentation
- 2 1 vs 3 1 vs 5 1
- ai vs machine learning vs deep learning
- python vs bash
- java edition vs windows 10 edition
- python vs anaconda programming
- java class vs object
- python list of lists example
- java file vs path
- python vs r