Create a class called OneDimArray then create a private generic array of type Object inside class, initialize array using constructor then implement the following methods inside class, then create a driver class called OneDimArrayTest for testing your program. Test your program with integers.
· + Boolean addItem(item)
· + Boolean addItemAt(index, item)
· + Object removeItemAt(index)
· + Object removeItem(index, item)
· + Object deleteItemIfOdd(item)
· + Boolean isEmpty()
· + Boolean isFull()
· + Object getItemAt(index)
· + Boolean setItem(index, item)
· + void swapItems(index1, index2)
OneDimArray.java
import java.util.*;
public class OneDimArray {
private ArrayList<Object> array;
public OneDimArray(){
array = new ArrayList<Object>();
}
public Boolean addItem(Object item){
return array.add(item);
}
public Boolean addItemAt(int index, Object item){
try {
array.add(index, item);
} catch(Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
public Object removeItemAt(int index){
Object o = array.get(index);
array.remove(index);
return o;
}
public Object removeItem(int index, Object item){
array.remove(index);
return item;
}
public Object deleteItemIfOdd(Object item){
if(array.indexOf(item)%2 != 0) array.remove(item);
return item;
}
public Boolean isEmpty(){
if(array.size() == 0){
return true;
}
return false;
}
public Boolean isFull(){
if(array.size() != 0){
return true;
}
return false;
}
public Object getItemAt(int index){
return array.get(index);
}
public Boolean setItem(int index, Object item){
try{
array.set(index,item);
}catch(Exception e){
System.out.println(e.getMessage());
return false;
}
return true;
}
public void swapItems(int index1, int index2){
Object a = array.get(index1);
Object b = array.get(index2);
array.set(index1,b);
array.set(index2,a);
}
}
OneDimArrayTest.java
import java.util.*;
public class OneDimArrayTest {
public static void main(String[] args) {
OneDimArray test = new OneDimArray();
System.out.println(test.addItem(10));
System.out.println(test.addItem(20));
System.out.println(test.addItem(30));
System.out.println(test.addItem(40));
System.out.println(test.addItemAt(3, 12));
System.out.println(test.removeItemAt(0));
System.out.println(test.removeItem(3, 100));
System.out.println(test.deleteItemIfOdd(4));
System.out.println(test.isEmpty());
System.out.println(test.isFull());
System.out.println(test.setItem(2, 220));
test.swapItems(2, 1);
System.out.println(test.getItemAt(2));
System.out.println(test.getItemAt(1));
}
}
Comments
Leave a comment