Last active
February 18, 2016 16:56
-
-
Save ibogun/6d7504dcb2c96405b04a to your computer and use it in GitHub Desktop.
List implementation using Generics types
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ListGenerics<Key> { | |
private Key[] list; | |
int size = 0; | |
int tail = 0; | |
final int INITIAL_SIZE = 8; | |
@SuppressWarnings("unchecked") | |
public ListGenerics() { | |
list = (Key[]) new Object[INITIAL_SIZE]; | |
} | |
@SuppressWarnings("unchecked") | |
public ListGenerics(int n) { | |
list = (Key[]) new Object[n]; | |
} | |
public boolean isFull() { | |
return (tail == list.length - 1); | |
} | |
public void insertEnd(Key v) { | |
if (!isFull()) { | |
list[tail] = v; | |
tail++; | |
size++; | |
} | |
} | |
public void insertBeginning(Key v) { | |
if(!isFull()) { | |
for (int i = tail - 1; i >= 0; i--) { | |
list[i+1] = list[i]; | |
} | |
list[0] =v; | |
tail++; | |
size++; | |
} | |
} | |
public boolean isEmpty() { | |
return (tail==0); | |
} | |
public void delete(Key v) { | |
if(!isEmpty()){ | |
int i = 0; | |
while( v!= list[i] && i < tail) i++; // find index of | |
// the element to delete | |
if (i < tail) { | |
for (int j = i; j <=tail - 2; j++) { // move all elements | |
// one index to the left | |
list[j] = list[j+1]; | |
} | |
size--; | |
tail--; | |
} | |
} | |
} | |
public String toString() { | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < size; i++) { | |
sb.append(list[i] +" "); | |
} | |
return new String(sb); | |
} | |
public static void main(String[] args) { | |
ListGenerics<String> l = new ListGenerics<String>(); | |
System.out.println("--- Insert in the end ---"); | |
l.insertEnd("12"); | |
l.insertEnd("3"); | |
l.insertEnd("33"); | |
l.insertEnd("7"); | |
l.insertEnd("2"); | |
l.insertEnd("40"); | |
System.out.println(l); | |
System.out.println("--- Insert in the beginning ---"); | |
l.insertBeginning("22"); | |
System.out.println(l); | |
System.out.println("--- Delete---"); | |
l.delete("33"); | |
System.out.println(l); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment