Skip to content

Instantly share code, notes, and snippets.

@KestindotC
Created May 27, 2017 09:05
Show Gist options
  • Save KestindotC/5c0fa5846529f6381e63ca0f3e2eb0dc to your computer and use it in GitHub Desktop.
Save KestindotC/5c0fa5846529f6381e63ca0f3e2eb0dc to your computer and use it in GitHub Desktop.
Java OOP Class Assignment#7
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.*;
/**
* Implementation of ArrayList using array data structure
* Other implementation (e.g. LinkList) were record in other files
* @author Kestin
*/
public class SimpleArrayList {
/**
* @param args the command line arguments
*/
public int size;
public int actual_size;
private Integer[] arr;
private void Callprinter(){
for (Integer ele:arr){
System.out.println(ele);
}
System.out.println("Actual size is: "+ this.actual_size);
}
public SimpleArrayList(int ini_size){
this.size = ini_size;
this.actual_size = ini_size;
arr = new Integer[size];
for (int i=0;i<size;i++){
arr[i] = new Integer(0);
//System.out.println(arr[i]);
}
}
public SimpleArrayList(){
this.size = 0;
this.actual_size = 0;
arr = new Integer[1];
}
// Default constuctor
public void add(Integer value){
if(this.actual_size==0) increaseListSize();
// Double the array size to save the element if array is going to be full
if(arr.length-this.actual_size <= arr.length/2){
increaseListSize();
}
arr[this.actual_size++] = value;
}
public Integer get(int index){
if(index < this.actual_size){
return arr[index];
}
else {
//throw new ArrayIndexOutOfBoundsException();
return null;
}
}
public Integer set(int index, Integer element){
if(index < actual_size){
Integer oldvalue = arr[index];
arr[index] = element;
return oldvalue;
}
else {
//throw new ArrayIndexOutOfBoundsException();
return null;
}
}
public boolean remove(Integer index){
if (arr[index] == null) return false;
if(index < this.actual_size){
Object garbage = arr[index];
arr[index] = null;
int tmp = index;
while(tmp < this.actual_size-1){
arr[tmp] = arr[tmp+1];
arr[tmp+1] = null;
tmp++;
}
this.actual_size--;
return true;
}
else {
return false;
//throw new ArrayIndexOutOfBoundsException();
}
}
public int size(){
return this.actual_size;
}
public void clear(){
arr = new Integer[1];
this.actual_size=0;
}
public boolean retainAll(SimpleArrayList l){
int flag = 0;
HashSet<Integer> mybag = new HashSet<Integer>();
for (int i = 0; i < l.size(); i++) {
mybag.add(l.get(i));
}
System.out.println(mybag);
Integer[] original = arr.clone();
for (int iter = 0; iter<actual_size;iter++){
if (mybag.contains(arr[iter])) {
continue;
}
else{
remove(iter);
flag =1;
}
}
if (flag==1) {
return true;
}
return false;
}
private void increaseListSize(){
arr = Arrays.copyOf(arr, arr.length*2);
}
public static void main(String[] args) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment