In: Computer Science
Convert arrays.py to Java.
‘’’’’’
File: arrays.py
An Array is like a list, but the client can use
Only [], len, iter, and str.
To instantiate, use
<variable> = Array(<capacity>, <optional fill value>)
The fill value is None by default.
‘’’’’’
class Array(object):
‘’’’’’Represents an array.’’’’’’
def__init__(self, capacity, fillValue = None):
‘’’’’’Capacity is the static size of the array.
fillValue is place at each position.’’’’’’
self.items = list()
for count in range(capacity):
self.items.append(fillValue)
def__len__(self):
‘’’’’’->The capacity of the array.’’’’’’
return len(self.items)
def__str__(self):
‘’’’’’->The string representation of the array.’’’’’’
return str(self.items)
def__iter__(self):
‘’’’’’Supports traversal with a for loop.’’’’’’
return iter(self.items)
def__getitem__(self, index):
‘’’’’’Subscript operator for access at index.’’’’’’
return self.items[index]
def__setitem__(self, index, newItem):
‘’’’’’Subscript operator for replacement at index.’’’’’’
self.items[index] = newItem
Program in java is given below:
import java.util.*;
import java.util.Arrays;
class Array {
String fillval="None";
String items[];
public Array(int capacity,String fillval) {
int x=capacity;
items=new String[capacity];
for(int count=0;count<capacity;count++)
{
items[count]=fillval;
}
}
public Array(int capacity) {
int x=capacity;
items=new String[capacity];
for(int count=0;count<capacity;count++)
{
items[count]=fillval;
}
}
public int len(){
return items.length;
}
public String str()
{
return Arrays.toString(items);
}
public String iter(int index)
{
return items[index];
}
public String getitem(int index)
{
return items[index];
}
void setitem(int index,String newi)
{
items[index]=newi;
}
}
public class example{
public static void main(String[] args) {
Array a = new Array(5);
System.out.println(a.len());
a.setitem(1,"2");
System.out.println(a.str());
System.out.println(a.iter(2));
System.out.println(a.getitem(0));
}
}
Output:
5 [None, 2, None, None, None] None None